Refactoring Deeply Nested Subqueries into Readable CTEs
Untangle nested subqueries into top-down CTE stories reviewers can follow.
In plain words
Pull each inner query out, give it a name, and list the steps in order.
Think of it like…
Rewriting a sentence full of nested brackets, "the total of (the orders of (customers who (signed up in 2026)))", as three short sentences in the order you'd explain them.
Where you’ve seen it
A 120-line churn report nests a subquery for active customers inside one for their last order inside one for days since that order, and repeats the active-customers subquery twice. The refactor produces four CTEs (active_customers, last_orders, days_inactive, churn_flags), a 6-line final SELECT, and an EXCEPT check showing zero differing rows against the old query.
Words you’ll hear
- Inside-out reading
- Nested subqueries must be read from the innermost level outward.
- Lift
- Move a subquery into a named CTE and reference it by name.
- Equivalence check
- Comparing old and new results with EXCEPT ALL in both directions.
- Correlated subquery
- A subquery that uses the outer row; it needs rewriting, not just lifting.
Visual diagram
Theory & example queries
The refactoring loop
Work from the inside out. Copy the innermost subquery into a CTE at the top, give it a name that describes its rows (active_customers, not x), and replace the subquery with that name. Run the query and compare results. Then do the next level. Small steps mean that when a difference appears, you know which step caused it.
As you go, replace SELECT * with explicit columns, give computed columns real names, and merge identical subqueries that appear in several places into one CTE. Correlated subqueries (WHERE o.created_at = (SELECT MAX(created_at) FROM orders WHERE customer_id = c.id)) can't simply be lifted because they depend on the outer row; rewrite them as a GROUP BY CTE joined back, a window function, or a LATERAL join.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT customer_id, daysFROM ( SELECT customer_id, current_date - last_order AS days FROM ( SELECT customer_id, MAX(created_at)::date AS last_order FROM orders GROUP BY customer_id ) a ) bWHERE days > 90;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
WITH last_orders AS ( SELECT customer_id, MAX(created_at)::date AS last_order FROM orders GROUP BY customer_id ), days_inactive AS ( SELECT customer_id, current_date - last_order AS days FROM last_orders )SELECT customer_id, daysFROM days_inactiveWHERE days > 90;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Equivalent result for both forms2 sample rows
| customer_id | days |
|---|---|
| 7 | 121 |
| 18 | 94 |
Note: The sample assumes a 2026-11-21 current_date and last-order dates roughly 121 and 94 days earlier. Both queries should return the same rows and are subject to the same filter boundary.
Before:
After:
Key takeaway: Lift innermost first, name rows, merge duplicates, rewrite correlated subqueries.
Proving nothing changed
Compare the two queries' results in both directions with EXCEPT ALL, which respects duplicate rows: (SELECT * FROM old_q EXCEPT ALL SELECT * FROM new_q) UNION ALL (SELECT * FROM new_q EXCEPT ALL SELECT * FROM old_q) should return zero rows. Also compare COUNT(*), because a plain EXCEPT ignores duplicates, and run the check on a few different date ranges or parameters.
Then compare EXPLAIN plans. In PostgreSQL 12+, CTEs referenced once are inlined, so the plan is usually identical. A CTE referenced twice is materialised by default, which might be faster (computed once) or slower (filters can't be pushed into it); NOT MATERIALIZED restores the old behaviour if needed. Older PostgreSQL versions always materialised CTEs, so check plans carefully there.
CREATE TEMP VIEW old_qAS (…old query…);CREATE TEMP VIEW new_qAS (…new query…);SELECT COUNT(*)FROM ((SELECT *FROM old_q EXCEPT ALLSELECT *FROM new_q) UNION ALL (SELECT *FROM new_q EXCEPT ALLSELECT *FROM old_q)) diff;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Symmetric-difference count1 sample row
| count |
|---|
| 0 |
Note: The two CREATE TEMP VIEW commands must first be replaced with executable queries and succeed. A count of 0 means no differing multiset rows; it does not by itself prove equivalent performance.
Expect 0.
Key takeaway: EXCEPT ALL both ways = 0 rows, then compare plans.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Capture the baseline
Save the original query and its result (or a view of it) so you have something to compare against.
CREATE TEMP VIEW old_qAS …When to use it & trade-offs
What it is
Refactoring a deeply nested query means turning subqueries that read inside out into CTEs that read top down, without changing the result. Lift the innermost subquery into a named CTE, replace it with the name, and repeat outward until the main query is a short SELECT over well-named steps. Then prove the new query returns exactly the same rows as the old one.
Why it matters: Legacy reports often have four or five levels of nesting, with aliases like x, y and sub1, and the same subquery copied in several places. Nobody wants to change them because nobody can follow them. Refactoring into CTEs makes the logic reviewable and removes duplication, and knowing how to prove equivalence is what makes the refactor safe to ship.
When to reach for it
- Legacy reports with three or more nesting levels
- Queries repeating the same subquery
- Before changing logic in a query nobody understands
When to avoid or be careful
- Refactoring and changing business logic in the same step
- Shipping a refactor without an equivalence check
- Lifting correlated subqueries without rewriting them
Ways to restructure a hard-to-read query
Strengths: Top-down reading; each step testable; no new objects.
Watch out: Steps can't be shared across queries.
Strengths: Defined once; reused everywhere.
Watch out: Another object to version and deploy.
Strengths: No change risk.
Watch out: Deep nesting stays unreadable and gets copied.
Interview signals & numbers to know
When this topic comes up
- “Make this query maintainable”
- “Nobody understands this report”
- Code review of SQL
- Correlated subqueries
- Proving two queries are equivalent
Benchmarks & rules of thumb
- 0
- rows from the two-way EXCEPT ALL check
- 1
- nesting level lifted per step
- PostgreSQL 12
- CTEs referenced once are inlined
Common mistakes & follow-ups
Common interview mistakes
- Fixing a bug while refactoring, so the equivalence check fails and you can't tell which change caused it.
- Checking with EXCEPT instead of EXCEPT ALL and missing that the new query drops duplicate rows.
- Turning a subquery used twice into a CTE on PostgreSQL 11 and getting a slower plan.
Likely interviewer follow-ups
- How would you prove a refactored query returns the same results?
- How do you refactor a correlated subquery?
- Can turning subqueries into CTEs change performance?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Refactoring Deeply Nested Subqueries into Readable CTEs with hands-on SQL practice and interview Q&A.