r/dataengineering • u/Lucky-Acadia-4828 • Jul 13 '26
Discussion How do you visualize SQL in your head?
Hi everyone,
I'm a software engineer that currently helping to build data team, so I work a lot as an "analyst" and build a bunch of data models.
As software engineer, I rarely need to work with large data transformation as a whole, and mostly focus on 1 row only. So it's easier for me to see through and wrap around my head.
I think the industry standard is using dbt, and writing a massive amount of transformation logic in sql. Most data models that I work with just nest 10-20+ CTEs to build a single table (this already decomposed in int/mart)
During code review, I'm hardly able to tell potential bugs (like joining using wrong key, potential row explosion, etc) at a glance, unlike when reviewing eg: python code.
Atm, I'm 50:50 asking claude to generate me a simple viz that could help me trace what happens in each cte transformation. Not always useful, but it slightly helps me.
How do you personally tackle this? Do you have an easier mental model that you want to share?
Thanks
43
u/itsmeChis Jul 13 '26
I think you should read up on Data Modeling techniques and practices. There are a lot of great resources available online for free. Start with understanding fact and dimensional data, then look into layers (my guess is you are doing all of your ETL in one sql model, rather than splitting into several).
6
u/SaltAndAncientBones Jul 13 '26
I was ten years into my SQL career when I asked that same question. A coworker suggest I read a book on set theory. Chapter 4 locked it all in for me. Once you can visualize sets you can you master SQL. I can't find the book on my shelf and I'm kicking myself; I think I left it in an old office. Regardless, it's basic set theory, so any beginner book will do. I've seen a lot of software engineers have a hard time switching over because they're thinking in loops and logic trees.
I think most people break it down in to bit sized pieces with CTEs and temp tables. Claude is my new go to. "Claude, summarize this query"
4
u/turbokat123 Jul 13 '26
I've been practicing SQL for complex problems and interviews as well. A recent technique i found that helps me is going backwards from the output. You start at what is the output you need and start working backward to fields it requires, up until the raw datasets you have.
This approach works well for large of data entities as well as smaller problems. Particularly it makes you see at which steps you need to aggregate, what fields you need to aggregate and consequently what you need to join.
I'd say for code review if you map the logical plan on paper first, you can pen potential issues at each step related to value errors, duplicates, key skews, data volume etc. depending on operations and then just address those during code review
3
u/read_at_own_risk Jul 13 '26
With an understanding of relational logic (Armstrong's laws, techniques like how to compute the closure of a relation) and knowledge of the candidate keys of each table, one can algebraically compute the candidate keys of a query's result set.
In less formal terms, that means that if I know the unique keys of the tables, I can look at a query and tell you exactly what columns will uniquely identify the output, where the row explosion happens, etc. It's not an art, it's a simple procedure, I can do it in my head for most queries in our system.
150
u/TheRealStepBot Jul 13 '26
By running it incrementally. Each cte, look at the table it produces the rows that are present or not present. Then slowly build your way up to the overall query
10
u/Old_Tourist_3774 Jul 13 '26
I am bad with imagining things so I just write them or see them in fact to then note mentality the expected behavior.
As per the problem, I focus on a key aspect to determine.
Say the key or row explosion you mentioned.
Why it happens? Because sql fetch everything that conforms to that constraint in simple terms.
6
u/ANGRYLATINCHANTING Jul 13 '26
As a series of lotus leaves, dancing in a Malaysian pond. Stored procedures are mantras, and code reviews are cultivation opportunities. Lucid ERDs and shame for everything else tho.
1
u/Lucky-Acadia-4828 Jul 16 '26
Thanks a lot for all the replies guys, I really appreciate it. Sorry I cannot reply all of you 1-1. I got one or two things I definitely have a blindspot on.
13
u/PatientlyAnxiously Jul 13 '26
10-20 CTE smells like machine generated or AI generated SQL. An experienced human dev would not make it as complicated IMO.
To write code that is easy to think about, I always define the granularity of my output in the first one (maybe two) tables in my FROM clause. All other joins are LEFT OUTER and do not affect granularity i.e. produce duplicates.
4
u/TeleTummies Jul 14 '26
The biggest tips I have are:
Understand cardinality between your datasets and understand primary / foreign key relationships. Whenever I’m working with a new dataset I build an ERD of it in my head (and on paper).
In an OLAP setting where uniqueness may not be enforceable or if the datasets are unreliable, run each dupe check proactively.
3
u/Life_Conversation_11 Jul 13 '26
Starting from the fact that a tool is only as good as the ppl who uses it, dbt might put your team on the right path (breaking down big models in several smaller, having tests in place etc)
These thing will make PR easier.
3
u/Additional_Candy_400 Jul 13 '26
Personally this is where I also struggle with reviewing SQL/DBT PRs compared to say Python.
As it's so context dependent on table which you often don't have sight of in the PR, it's difficult. You can step through each CTE individually, or just have robust assertion standards to catch common mistakes.
But ideally you'd be having someone review who already has domain knowledge of the underlying tables.
3
u/MeditatingSheep Jul 15 '26 edited Jul 16 '26
I learned relational algebra in school, and its applications to database implementations and query optimizing. Was shocked to see how many crazy tutorials there are for simple SQL statements.
Translating between math and DB-speak helped me personally:
SQL is declarative, not procedural. You must test your database, run EXPLAIN SQL command, read the docs (and still test it), or consult your DBA.
You want to avoid reading all records in table A joined to all records in table B, generally, but it's tragically easy to make this mistake everywhere. Avoid it by reading only from specific partitions, using an INDEX, clusters, and consider taking some compute load off the prod DB-server by processing in more smaller chunks in your (Python) application or even writing to your disk. But caching like this can also hurt the app server, be careful. Unless you're running on a container, which is generally advised.
In a distributed context (Spark, BigQuery SQL, etc) you want to take advantage of native row ordering, clustering, and reduce shuffles. Memory management in app config paired with efficient task sizes helps speed up jobs and reduce compute used.
2
u/maggi-paglu Jul 13 '26
You need to edit the cte's and add select statements whereever needed, just you do in code through print function. Its something that comes with 3-4 months of work practice. This is one thing which claude eont help you with, so need to learn, its very important skill.
2
u/MrMisterShin Jul 13 '26
The issues you mentioned in your code review description above, to a certain extent can be identified using Explain Plan. So that you can see how the SQL optimiser is interpreting the SQL. (It will be a bit fiddly over so many CTE)
VISUALLY the ERD and data dictionary would help too.
2
u/Itchy_bunghole11 Jul 13 '26
I visualize SQL as overlapping SET theory arithmetic.
2
u/Almostasleeprightnow Jul 13 '26
If you can get stuff working in notebooks that can help because you can output views of subsets of your dataset as you go to verify steps
2
u/Better-Credit6701 Jul 13 '26
CTEs are great with smaller databases but won't work well with larger databases. Temp tables would work better since you can index it and it will use statics plus reused within the query.
I think about large queries by breaking it into smaller chunks.
2
u/rotterdamn8 Jul 13 '26
For each CTE or subquery I copy and paste table snippets (first 10 rows for example) into Excel.
I never had to do this with 20 CTEs but up to five it helps me see it. I also might highlight join keys.
2
u/Juxta_Drewski Jul 13 '26
I do venn diagrams or “graph paper chunks” that you cut apart and glue together differently as my mental model.
The latter one helps a lot when trying to suss out which join keys do what
2
u/Substantial-Cow-8958 Jul 14 '26
Also, check if you could break your scripts into temp/tables. Just so you could debug each cte, check the rows, etc..
2
u/badsignalnow Jul 14 '26
I visualize it as sets using filtering and joining as operations on those sets. Subsets. Union. Intersection.
Layer on top of that how the database functions to build those sets. Indexes, scans, sequence of oprtations.
From a business perspective, how the tables relate through business relationships.
2
u/robberviet Jul 14 '26
If you are swe, think by how db engine are implemented: how sort merge hash join works, how data is stored, get from file, how areay in memory works, how query optimizing works...
2
u/Yavuz_Selim Jul 14 '26
Data set left, data set right, and then add on top of it. (It's basically starting with a base table, and then adding data (columns) into it.)
Granularity is very important for me. So once you know the detail level you want/need, the rest is just making the data sets to that same granularity.
I also of course do spotchecks in-between. I sometimes expect exactly one row, sometimes 3, or 5 or 25. I run the query - of there is more than expected, some temp table needs a small adjustment.
2
u/doc_marty_mcbrown Jul 14 '26
Im fortunate enough to have a Dataiku license, so im able to apply a modular pipeline dedign. Outputting datasets along the way, i can detect , where exactly a data explossion , or transformation error happened. Also allowing me to write ad-hoc queries to perform RCA and analysis, or data extracts on CTE sections of the OBT (one big table).
I know its a luxury to have this tool, and i dont even use it for its main data science/ AI dev work.
Do I need to have Dataiku to do the work, no, but it is is usuful for the very questions you've laid out. I can do all the DEV work in this sandbox type of environment and QA many of the issues, way before it reaches customer. Plus the benefit of visualizing the pipeline. And only push to PROD already tested pipelines.
2
u/mschmitt1217 Jul 14 '26
2
u/living_with_dogs Jul 15 '26
I visualise SQL like a one of those falling ball games - maybe bagatelle, pachinko, or plinko.
You put balls (records) in at the top and need to understand where they land. Your happy path at the end of the pipeline is your expected output. Joins, filters all stop records flowing down and represent other places / pots / buckets where balls can land.
It doesn’t have to be just SQL - all data pipelines do the same thing (basically anything DAG-like)
Well written SQL lets me know the intended scoring zone, where data will drop out, and easily tell me why records have not landed where expected.
Bad SQL is more like actual plinko where the ball randomly bounces and you have idea where it will land
2
u/Ill_Freedom_6666 Jul 16 '26
i mostly track row counts and join cardinality through each cte, that catches more bugs than trying to picture the whole query at once
1
u/AlexV_96 Jul 18 '26
A flow chart with transofrmations instructions in the arrows and individual tables in the nodes/boxes
Some charts are single lines others have multiple branches that end up in a single table.
Only when it becomes too difficult to memorize I draw the actual "flow chart"
1
u/Yahia08 Jul 18 '26 edited Jul 18 '26
I see squares/rectangles for the tables, trees for groups, etc.
0
u/umlcat Jul 13 '26
Did you learned Relational Algebra before SQL ???
Because that is the way I visualize SQL, as composed Relational Algebra operations ...
0
u/Educational_Creme376 Jul 14 '26
I always thought CTEs were for lazy people who couldn’t write SQL.
1
u/[deleted] Oct 23 '26
[removed] — view removed comment