The SQL habit that separates juniors from seniors
If your SQL still lives in nested subqueries, read this.
Last week, we broke down SQL's joins.
Today we go one layer up. Not stitching tables together, but organizing the whole query so it reads like structured code instead of a wall of nested logic.
Here’s this week’s cheatsheet 👇🏻
Ever inherited a SQL query from someone who left three months ago?
Nothing lines up. The same metric is calculated three different ways in three different places. You can’t tell which subquery feeds which. Two hours in, you’re still just trying to map what the thing is trying to do.
That’s the problem CTEs solve.
What a CTE actually is
A CTE (Common Table Expression) is a named, temporary result set. You define it once at the top of a query and reference it as many times as you need below.
Every CTE starts with WITH.
Think of them as building blocks. Each block does one clear job. The final query snaps the blocks together.
Why WITH changes how queries read
Without CTEs, complex logic hides inside nested subqueries buried three levels deep. You read from the inside out.
With CTEs, every helper table sits at the top of the query. You read top to bottom: block 1, block 2, block 3, then the final SELECT. Linear. Named. Debuggable.
You can also chain them. Block 3 can pull from block 2, which pulled from block 1. That is how one clean query replaces a tangle of joins and subqueries.
The reusability layer
Once a CTE is defined, you reference it as many times as you want inside that query.
The bigger win is across your team. When everyone builds on the same named CTEs (active_users, monthly_revenue, churned_accounts), the same metric gets calculated the same way, everywhere. No more “why does your revenue number differ from mine”.
CTEs turn SQL from a wall of nested logic into code that documents itself.
Next Sunday I’ll walk through a full modular query end to end, so you can see the blocks click into place.
—Josep
Are you still here? 🧐
👉🏻 I want this newsletter to be useful, so please let me know your feedback!
Before you go, tap the 💚 button at the bottom of this email to show your support, it really helps and means a lot!
Any doubt? Let’s start a conversation! 👇🏻
Want to get more of my content? 🙋🏻♂️
Reach me on:
LinkedIn and X (Twitter) to get daily posts about Data Science.
My Medium Blog to learn more about Data Science, Machine Learning, and AI.
Just email me at rfeers@gmail.com for any inquiries or to ask for help! 🤓








