r/SQL • u/Acceptable-Sense4601 • Jan 17 '26
Discussion Fairly new to SQL. Whats some long SQL as far as lines of code?
So i normally write brief SQL. Normally 30 or so lines cover what i need to query. However IT recently gave me the SQL and access to the tables behind a PowerBuilder report and it was close to 300 lines of code. Lots of outer joins and a bunch of CASE logic. So just curious how wild does SQL usually get in the business world?
24
Upvotes
61
u/samwise970 Jan 17 '26 edited 9d ago
The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.
Unwritten brave history party sparrow mysterious engine flowery
13
u/Due_Flatworm_8229 Jan 17 '26 edited Jan 18 '26
I work in healthcare. Have worked with several different companies and several different systems in this domain. Below is an obviously very rough estimate of line counts from my experience.
Lines : estimated % frequency
0-500 : 10%
500-1000 : 25%
1000 - 5000 : 50%
5000+ : 15%
Edit: also, there seems to be a notion in the comments that lots of lines equates to slow running queries. You can have a 5000+ line query that runs in seconds. It’s all about optimization which is an art by itself.
8
u/comfy_cactus Jan 17 '26
A lot of it depends on the complexity of the data requested. I work in healthcare and my longest query is 1,900 lines. The data request needed all sorts of different window functions relative to different, respective dates/topics.
Fortunately this query was for research data so we only need to run it once. This is fortunate because the runtime is about 20 minutes. Could the query be optimized to bring that down? Absolutely. But an unnecessary use of dev time since we only run it once
4
u/Infamous_Welder_4349 Jan 17 '26
I have some over 4,000 lines. They are mostly auditing reports. They check dozens of conditions and the union the results.
3
u/JoeHaveman Jan 17 '26
I recently wrote another COBRA benefits extract. The report is based on tables for benefits, employees, contact, dependents, deductions, etc. There are 12 different reasons why you are on the report and subsequently receive a cobra letter. Turning 26, death, divorce, termination, etc. The output requires the participant record first followed by the recipient records.
The whole, single query was dozens of CTE’s. Included case, replace, coalesce, rank, joins, left joins, etc. Fairly basic, normal SQL. But you just need to know how to use data to build your own building blocks.
It takes a developer mindset. How to build using SQL. And to not give up. Try every possibility until you get it working.
3
u/Awkward_Broccoli_997 Jan 17 '26
Two bits of advice for people learning SQL (which may or may not be you OP, you didn't say):
One, everything is downstream of the joins - read those first. A 300 line report may actually be just a few table, view or subquery joins and a whole lot of field manipulation. The field munging just isn't terribly important to think about until you're thinking about those fields in particular.
Two, if there are subqueries, read those and think of them in terms of the structure of their result. Run the subqueries - what's the shape of the data? Getting what you want? Great, think of that as a table, and now your brain has a much easier problem to organize.
Regardless of how you tackle it though, probably the single worst way to manage it is to just try to read it from beginning to end. It wasn't written that way, and it won't be readable that way.
2
u/Wassini Jan 17 '26
I sometimes make sql statements with 150-200 lines of code. Not very often, but it happens.
2
u/jagaddjag Jan 17 '26
Some time bad coding
2
u/orz-_-orz Jan 17 '26
My company pipeline consists of many SQL scripts, some scripts have 1000+ lines of SQL codes.
2
u/barelytethered Jan 17 '26 edited Jan 17 '26
My company has a couple of legacy applications where they interact w/ the database through a collection of stored procedures. In the mid-2000s, it was common practice where a stored procedure would group functionality in the same domain, and which query is run is determined by the parameters.
The result of this approach is we have a few stored procedures that are 5000+ lines long. 90% of the time, the queries in the stored procedure are less than 100 lines long. The longest query I've run into is roughly 1800 lines long, and an absolute mess of nested joins. Unfortunately it basically drives the entire application.
- edit. spelling & grammar
2
u/Copakela Jan 17 '26
I’ve worked in various industries through my career (energy, banking, software, transport) and regularly come across queries >1000 rows. The thing you have to consider is, what do you want your query/sp to do? What’s the required end result? If that needs 1000 rows or so, that’s what you write. If you can split it up into 2 or 3 sp’s then it probably would be easier to manage or debug if you have good error logging and can pinpoint where things go wrong. But sometimes if you’re dealing with a file import and whatever transformations you need to get your end result, it’ll take as much as it takes.
2
u/ZarehD Jan 17 '26
How "wild" does SQL code get in biz world?
I worked for a major health insurer. I can answer this in one word: Very!
The SQL was too hairy (and fragile) to actually fix, so we had a bunch of "data analysts" whose job it was to un-fuck people's accounts when they fell into various "edge" cases (but only when they complained, of course).
5
u/spacebassace Jan 17 '26
Healthcare worker here that focuses on process and workflow improvement for a large healthcare system. I'd say my queries can range anywhere from a few hundred lines of code to upwards of 4000. I include lots of inline comments as well so I have a clear picture of purpose of each segment.
We work with hospitalized patient data so it's pulling a lot of lab results, meds, procedures, patient notes, diagnoses, patient movement through hospital wards, surgical information, and misc other documentation to measure and optimize workflow processes among different types of patients.
Irrespective of the length of any code, clean, efficient, readable code is key for maintainability and future enhancements.
4
u/kagato87 MS SQL Jan 17 '26
Length means nothing. It's complexity and number of joins.
I have simple 300 line queries because of a single case statement that covers a hundred codes (finally got the enum put into the db last year), and complex 20 line queries. I have thousand line test scripts.
When writing sql, 300 lines isn't much as soon as you put one line per fact. You're also looking at a folded query, and those often look a lot larger than they need to be. Simolifying them shows the truth - they're maybe 50 lines.
As for performance, sql engines have decades of refinement in their query planning and processing. They can detect and reduce those redundancies and see through the mess (mostly).
So don't sweat length. It's meaningless. A query is too big when you can't conceptually hold what it's doing in your head (general programming thing).
1
u/Glum_Cheesecake9859 Jan 17 '26
It's like saying why is the marathon so long? I wish the marathon was 100M.
1
u/lemeiux1 Jan 17 '26
I mean it really depends on what you are doing and your role, but I have some more complex stored procedures that can have up to 1000 lines.
1
u/paultherobert Jan 17 '26
I did a trial balance for an ERP that was pretty complex and it was like 1500 lines. Id consider that an exception, but 200-500 is pretty normal for me. But I also structure the layout of my SQL very specifically to be organized and easily read.
1
u/titpetric Jan 17 '26
Built a very high traffic news website and the bearable metrics were to a maximum of about 100 lines for a single query. A complicated query would basically fit on screen, and we didn't put much business logic into 95% of the queries.
I'd say beyond 5 joins and 100 lines you're in cursed territory, but, with a good dba around tolerance could be a lot higher. If most queries are simple, most queries are correct.
1
u/After-Entry5718 Jan 17 '26
Typically 2-500 for me creating custom marketing audiences and data pipelines for tableau.
1
u/[deleted] Jan 17 '26
Very normal 500-1500 lines. I work with financial derivatives.
1
u/sam_cat Jan 17 '26
Biggest I have written was a single process migrating data from multiple system into one place, transforming and preparing a lot of data warehouses from it along with an outbound data feed. Think that totalled about 30k lines (Inc comments, linebreaks etc...) but was multiple SP's, tvf's views etc.
Most projects are nowhere near this, but we needed this to be very robust, self healing and cope with all sorts of potential issues, along with audit trail and extensive logging. No longer work there, but still friends with people that do, code is still in use and 'just works'.
1
u/AbbreviationsDue3834 Jan 17 '26
Are you learning this for a job requirement or a hobby or? Why do people just up and learn this stuff? Future job prospects?
1
u/Glathull Jan 18 '26
I was once the unfortunate maintainer of a stored procedure that was a bit over 60 thousand lines of code. 😞
3
u/Candid_Finding3087 Jan 17 '26
I think it depends a lot on the architecture and data model of the db. Highly normalized dbs will involve more joins. Formatting is also big. We have an engineer whose queries and sps are probably half the lines they would be if I wrote them. I can’t say much about it cause he is strongest pure coder we have. All that said almost all of our critical queries, views, sps are 300-2000 lines. The longer ones are usually modular and involve unions, case statements and nested subqueries. The query that gets repeated is usually 300-500 lines.
3
u/ClassicNut430608 Jan 17 '26
In the MSSQL flavor, you can use the SSMS client to 'View Dependencies'. This tool will give you a 'feeling' on how complex the query really is. The more the query depends on the more complex. The number of lines can be misleading, especially when the code is heavily documented or has received a lot of updates over time.
The CASE logic is generally a way to have concise code, handling 'odd cases' in-line. Like CTEs, #temptables. it is one of the building blocks of resilient query code.
In the SQL shops I had been consulting with for the last 20 years, I have seen 10 to 30% of queries larger than 1,000 lines. Some of these running every 10 or 20 seconds - 24/7.
When large queries block other queries, the larger these are, the more difficult to quickly debug.
2
u/iwillupvoteyourface Jan 17 '26
I have a query for migrating data in the same database between tables that using a lot of merge statements that is 8k ish lines. It was inherited it’s a bit of a mess but slowly being cleaned up.
2
u/Lurch1400 Jan 17 '26
My own philosophy is: Simple, Fast, Maintainable
Doesn’t matter how long it is. In addition, some developers insist on using the DRY (don’t repeat yourself) method, but imo, that’s not always helpful in SQL.
2
u/Separate-Leather-615 Jan 17 '26
I wrote one for a bank with huge data on rating.. It was around 2000 lines Query was taking 1 hour to run
2
u/Bombadil3456 Jan 17 '26
My longest query is around 3000 lines but I use line breaks so probably around 2000-2500 lines of pure sql
2
u/CFAF800 Jan 17 '26
I once had to create a SSRS report which had like 60 questions and answers for a detailed case report.
Another developer was assigned this task and they couldnt do it even after I gave them a base query to do for one question, I wrote the whole code in 3 days or so and it was 3000 lines long at the end of it but very easy to read though.
Golden rule of writing code I always abide by - write code which is easy to debug and not easy to write
2
u/rjromeojames Jan 17 '26
We have several triggers with more than 5k lines of code
2
u/Say_My_Name_Son Jan 18 '26
I'm with an automotive parts retailer.
Sometimes it's as simple as 20 lines to get a summary of sales dollars by brand, year over year.
Sometimes you're dealing with purchase orders, when they were received, and all of the locations that they were put away into the warehouse.
Then there are the secret sauce algorithms of which products we want to stock and how much and to which warehouse(s).
It can get complex.
2
u/dittybopper_05H Jan 19 '26
I’ve had a number I’ve written that exceeded 1,000 lines, but generally they are a bunch of separate statements strung into a single script that needs to be run. Also, that includes a bunch of comments, and empty lines to make the code readable.
2
u/Red__M_M Jan 21 '26
I’ve seen 8,000 lines of garbage that was THE critical process.
Personally, I will commonly write 300 or so lines, but that is driven by a very clean and elegant formatting pattern. If I am selecting 50 fields, then I write that using 50 rows. If it needs a group by clause, then that is 50 more rows. Every field that is in a join is a separate line. Etc.
I use clean, simple, and short queries writing to temp tables or CTEs rather than shorter but more complex code that does everything in one go. I can show my 300 lines to a lay person and they will understand it. Maintenance is easy. The code is self documenting.
Rather than grading yourself by line count, grade yourself by what you think of the code 2 years later when you have long forgotten why you wrote the code. Is it easy to understand and modify or are you exhausted just by looking at it?
1
u/OO_Ben Postgres - Retail Analytics Jan 17 '26
My primary transaction query for the company I work for is 3500 lines long. Lots of messy base data I have to clean. But half of that is for standard transactions, while the other half pulls strictly gift card data using the same logic. So realistically it's like 1750 lines or so.
Sounds like a lot, but it's surprisingly efficient for what I need on a nightly update. Not crazy, but around 30 seconds depending on how many new lines we got on the base tables the day before. I'm sure therr are gains to be had, but I had way higher priorities than inking out an extra 10 a seconds of efficiency on that lol
1
u/zbignew Jan 18 '26
Lots of systems use programmatically generated SQL so length is basically unlimited.
I joined a company with some 8000 line scripts that had no code re-use, so breaking them into smaller stored procedures and functions and shrinking them was pretty easy.
None of the individual queries were complicated or over 300 lines. But they might have 10 queries in a row with nearly identical content.
1
u/WhiteBloodCells90 Jan 18 '26
For our one report, Ive used CTEs and the lines of code are around 800. I have already transformed the data in multiple views however still the query is heavy. This report consists of Full years balances of previous years, actual balance of CY months, Plan values of next three months amd multiple columns of variances. In the report we have dynamic labels based on the filter.
1
u/garlicpastee Jan 18 '26
That depends what exactly do you mean. Some tsql blocks can be as long as 10k lines long, but if you mean single statements, usually good ones that aren't too opaque to the engine close before you reach 100 lines. To be honest you could rewrite some etl jobs into single long statements with tens of cte's, but why would you - if we find something like that at work, it gets refactored fast.
In short - you could find some obnoxiously long code that has thousands of lines, but usually the logic should've been split up into smaller chunks, so I'd say a single statement with 100 lines is already too much. But if you include tsql and treat ie. stored procedures as just some SQL, then it could be 10000 and be fine.
1
u/rjmartin73 Jan 18 '26
It all depends. I inherited an environment with many stored procedures with 4-5k lines. A lot of ctes, temp tables, etc. Total nightmares for performance.
1
u/[deleted] Jan 18 '26
I have a request . I want to practice such Queries
i won't say im a noob , I know SQL but haven't worked Professionally
And no one is hiring in my demographic
So i want to write queries like that , Can you somehow Give me such tables and Problem Statements.
1
u/Sexy_Koala_Juice DuckDB Jan 18 '26
There’s one at work that’s about 4000 lines. Granted it could be improved in some areas, since I think it’s been used/added to over multiple different vendors.
The longest I’ve written myself is about 700ish.
I find if you have sensible CTEs and documentation that accurately describe the steps taken then it can be somewhat manageable. But yeah anything more than 500 it’s time to start looking at tools DBT to see if your queries can be split up somewhat more systematically
1
u/carlovski99 Jan 18 '26
Generated SQL can infamously be very long and suboptimal. Especially with lots of case statements deciding stuff that should really be in the data, rather than hardcoded in the query.
1
u/cwjinc Jan 18 '26
SQL statements are single statements, so basically one line.
That line can get pretty wild ;)
1
u/rargghh Jan 19 '26
lines of code isn't as big as a problem of sprocs calling sprocs and you find yourself 10 calls deep wondering what you were chasing in the first place
especially now with AI making solid leaps, I wouldn't trust it yet to do some things, but it's good at summarizing and finding what you're looking for amongst many lines
300 lines of code I would call very small, with average comments and revision history on a sproc or function you could be looking at a minimum of 100 lines
300 lines on a single query? That's a bit much but it reallllly depends on what you're doing, alot of stuff can get broken up
1
u/TeRmInAtOr2p0 Jan 20 '26
It gets wild but there will always be ways to optimize your queries and that's the most important part.
1
u/[deleted] Jan 21 '26
1 line. I don't use line breaks
1
u/nerdworld199 May 13 '26
Enterprise SQL can get pretty wild. Once you get into reporting systems, legacy apps, or data warehouses, it’s not unusual to see hundreds or even thousands of lines . especially with layered business rules, CASE statements, temp tables, CTEs, and tons of joins. A lot of those reports evolve over years with different people adding logic over time. I feel like if you’re comfortable reading through a 300-line query already you’re getting exposure to the real-world side of SQL beyond basic querying.
0
u/[deleted] Jan 17 '26
[deleted] — view deleted comment
2
u/[deleted] Jan 17 '26
[removed] — view removed comment
1
u/[deleted] Jan 17 '26
[removed] — view removed comment