r/SQL • u/Consistent_Law3620 • Jun 27 '26
Discussion Need advice: Understanding complex SQL scripts written by others
Hi everyone,
I need some advice from experienced SQL developers. I have switched from different role to data engineering 6 months back.
I consider myself good/medium level at writing SQL queries and solving problems from scratch. However, I struggle when I have to understand large existing SQL scripts (300–500+ lines).
I often get confused about:
Where the execution starts.How different parts of the script are connected.
Which variables, CTEs, stored procedures, or temporary tables are affecting the final output.
How to mentally trace the flow of the script.
Because of this, reading someone else's code takes me much longer than writing my own.
How did you improve this skill? Are there any techniques, exercises, books, or real-world practices that helped you become comfortable reading large SQL scripts?
Also, is this something that simply improves with experience, or is there a structured way to learn it?
I'd really appreciate any advice. Thank you!
45
u/DragonflyHumble Jun 27 '26
For analyzing any query, first understand the grain or unique combination of any table/subquery from the FROM clause and then read it will be much clear
13
u/jaxjags2100 Jun 27 '26
Drop the query into an LLM and ask it to analyze and write inline comments to explain what the query is doing with business logic and plain English
27
u/Stormraughtz Jun 27 '26
Couple steps I do:
Format the entire script into how you would write it.
Break the code into sections, CTEs, temps.
Then follow the flow.
Yes brain hurt, yes is hard, yes is time.
10
u/ChristianPacifist Jun 27 '26
Use Notepad++ or another tool where it highlights the opening and closing parenthesis red to see what parts are in which parenthesis.
42
u/Hobob_ Jun 27 '26
Use ai
3
u/big_poppa_man Jun 27 '26
This is probably one of the most difficult aspects of a SQL heavy job. What I do it I'll run the code and limit the code to 5 rows of output. I'll paste that into a Google sheet. Then I open a new tab in my text editor and paste the code in there. Then I'll edit the code in my own preferred format. It makes it easier to read it. For examples, I don't like subqueries, so I'll rewrite it as a CTE. I'll use my own aliases (I like single or double letters). This helps me.
3
u/Ginger-Dumpling Jun 27 '26
Line count is a terrible way to describe SQL complexity. Use a code editor that supports collapsing/code-folding, slap a comment on the top of select block describing what it does, collapse it to one line, rinse, repeat until you can see what the whole thing is doing on one screen.
Wouldn't toss out using a queue visualizer or AI if your org has/allows them. Some places can be stringent with what you're allowed to use.
3
u/Aeon2121 Jun 28 '26
I wish you luck! I’ve been reverse engineering some 3k+ line business dmls made in a production environment with no dba in sight. Best bit of advice is break each portion apart for logic and make a flow chart. I’ve bastardized some flow charts by calling them erds just to understand where the data is flowing into different tables.
4
u/SummerEquinox71 Jun 27 '26
In the past, I have used (drawn by hand with pen and paper) query diagrams. You can google for details but it primarily involves drawing boxes for tables in the from clause as a hierarchy with arrows originating from the fk table to the pk table. You can add the filter conditions by the arrow lines. Over time you will get used to it and drawing diagrams will become a mental process.
2
u/wildjackalope Jun 27 '26
Yes, it gets better with experience particularly as you become more familiar with a data set. This can be challenging as a DE as you’re often stretched across multiple sets.
Some of this you do need to grind through but the thing that will probably help you the most is understanding what the engine is doing. The simplest form of this is understanding that the query starts at FROM and work your way out. With complex queries that are utilizing multiple CTEs, etc. you just start pulling the thread and working out from there. This is a skill and needs to be developed.
2
u/SkullLeader Jun 27 '26
Honest answer? There's no substitution here for repetition and experience.
In any case, try to break down each piece, understand what its doing, write down a one or two sentence summary of each piece, in order. Then read it back.
Make sure you understand the tables/views/functions being used first, and the data itself. Complex code + I don't even know what the data is that he's querying or how its structured means you're gonna have a tough time, regardless.
I agree with commenter below me - when you are looking at SELECTs, look first at the FROM clause, the joins, and the WHERE / GROUP BY / HAVING clauses if they are present. Usually the columns he's selecting or calculating are less important to understanding what's going on.
2
u/ax0r7ag0z Jun 27 '26
Nice try AI
2
u/AnalistaDeDados_ Jun 29 '26
Vivo isso diariamente ... tenho que dar manutenção e entender scripts SQL de mais de 15 anos atrás. Feito por pessoas que não estão na empresa, passaram mais de 20 pessoas aqui e cada uma com um jeito diferente de programar ... uma verdadeira salada.
Hoje eu uso 100% do Gemini pra fazer esse trabalho de entendimento pra mim, jogo no prompt e ele me retorna tudo que um script faz ... não perco meu tempo mais fazendo essa analise inicial.
1
u/Glitch_In_The_Data Jun 27 '26
Can you not use one of the AI tools to help especially if you want to understand existing SQL scripts?
The challenge I find with existing SQLs is that they are likely to have evolved over time. While you may learn something from them, it is also likely to confuse you more and may teach you a bad approach.
So, may be use AI to understand the existing SQL and then rewrite based on your own approach to see if are able to achieve the same results. And again use AI to evaluate or score your work.
It does take more time to understand code written by others. So, you are not alone. And over time, your skills will get better.
Do you use a specific tool at the moment? Asking because modern tools now have AI embedded in them.
1
u/big_poppa_man Jun 27 '26
Also, it's more difficult to read SQL code imo because there's the fact that it takes a long time to learn how data works and is connected.
1
u/lalaluna05 Jun 27 '26
I have to do this a lot when re-writing or adding to legacy code (most of the time Frankencoded over years and years). I add comments as I go to what each block does. I will reformat sometimes so that I can more easily separate code chunks.
Other times I slap stuff into excel and go field by field and table by table adding the criteria and data manipulation so I have the whole picture.
AI is fine and good but for me personally, I need to “see” the shape and architecture of the query.
1
u/Substantial-Click321 Jun 27 '26
Don’t read from SELECT. Start by reading joins and FROM.
1
u/Rohml Jun 27 '26
A lot of SQL codes can be separated by blocks of DML commands with lines of codes detailing what those DML commands specify (what fields to select, insert, update, or delete, what criteria do they filter on, etc.) and from there you can break them down one by one.
Take it step by step, each step it wants to do something and often it is just to ready data for the next step until you get to your final output.
You get better at it as you gain experience in seeing the intent of what the developer wanted to do and the purpose of the script: what it starts with vs. what you get in the end.
1
u/venkat_deepsql Jun 27 '26
Essentially query execution is like a tree. There will be table scans in the bottom and selects on the top. In between you can see filters, joins, sorts, temporary tables etc. You don't need AI for this, simply do EXPLAIN <query>, most of the query engines shows you clearly the execution plan. You can EXPLAIN ANALYZE to understand the actual execution tree after the query is run.
It's easy to recommend AI. but the truth is, your chatGPT or Claude might not have access to the database you are running. So if they do, then yes, they can analyze the query and explain you in easy to understand terms.
1
u/murse1212 Jun 27 '26
Something I started doing a few years back, I’ll copy the query and paste it into a text editor and I will go CTE by CTE and above each I’ll
Comment a line for what the CTE does and another for what it’s grain is. This makes it exponentially easier to read it in a ‘flow sate’ from start to finish and helps to surface any potential silent fan outs due to grain mismatch
1
u/age_of_unreason Jun 27 '26
I think that’s normal. Try separating each select query and run each one separately and do a CTAS to store to a table if you need to use it for joins in downsteam code while working through it. If one query uses a variable from another query, substitute a dummy variable. Keep working through it. It takes time and patience. I was in the same boat 6 months in. Even today after 4+ years it still takes a little more time to understand someone else’s code and what their intent was. When you write the code it’s different because you naturally are more familiar with what you wrote and why.
1
u/dontich Jun 27 '26
Yeah agree with the AI guy — usually it will give me the basics of what they were trying to do. Then will go for it sub queue by sub queue and try to understand all the joins. Will also write test queries in places to make sure things work.
1
u/ChaosEngine-6502 Jun 28 '26
I find a starting point for me is reformatting the script into my preferred style (indentation, uppercase key words, etc) - practically every script written by someone else I've ever had to deal with is poorly formatted with some weird idiosyncrasies that need dealing with.
This clean-up process generally gives me a better understanding of what the script is doing because it forces me to become familiar with it. Some might think it a bit of a waste of time, but I generally find it's the best place to start.
Footnote: revisiting stored procedures I haven't touched in a couple of years can be equally confusing...good comments and layout are a big help!
1
u/vbnotthecity Jul 25 '26
start from the last cte and work backward to the source tables. after years managing dbt and airflow stacks, i found that using tools like dbt labs, datafold, or Altimate AI helps cut down the manual tracing time by half when you're buried in spaghetti code.
1
u/speadskater Jun 27 '26
Find ways to break every subquery into parts and map the joins manually. Find a single example and use that as constants to pull the subqueries out into new windows to test with.
1
u/Ok_Carpet_9510 Jun 27 '26
You can drop the script in LLM and ask it to explain the code, and give a simpler version of it.