Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 68/ 160
04. Subqueries & Common Table Expressions (CTEs)

Refactoring Deeply Nested Subqueries into Readable CTEs

Untangle nested subqueries into top-down CTE stories reviewers can follow.

IntermediateRefactor · Nested → CTE3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Before and afterQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  customer_id,3  days4FROM5  (6    SELECT7      customer_id,8      current_date - last_order AS days9    FROM10      (11        SELECT12          customer_id,13          MAX(created_at)::date AS last_order14        FROM15          orders16        GROUP BY17          customer_id18      ) a19  ) b20WHERE21  days > 90;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/21
query.sql
1WITH2  last_orders AS (3    SELECT4      customer_id,5      MAX(created_at)::date AS last_order6    FROM7      orders8    GROUP BY9      customer_id10  ),11  days_inactive AS (12    SELECT13      customer_id,14      current_date - last_order AS days15    FROM16      last_orders17  )18SELECT19  customer_id,20  days21FROM22  days_inactive23WHERE24  days > 90;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/24
3OutputInspect the representative rows, affected-row count, plan, or command status.
Equivalent result for both forms2 sample rows
Equivalent result for both forms
customer_iddays
7121
1894

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Equivalence check with viewsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1CREATE TEMP VIEW old_q2AS (…old query…);3CREATE TEMP VIEW new_q4AS (…new query…);5SELECT COUNT(*)6FROM ((7SELECT *8FROM old_q EXCEPT ALL9SELECT *10FROM new_q) UNION ALL (11SELECT *12FROM new_q EXCEPT ALL13SELECT *14FROM old_q)) diff;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Symmetric-difference count1 sample row
Symmetric-difference count
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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Expect 0.

Key takeaway: EXCEPT ALL both ways = 0 rows, then compare plans.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Before

Capture the baseline

Save the original query and its result (or a view of it) so you have something to compare against.

SQL at this stepReadable preview
1CREATE TEMP VIEW old_q2AS …
What to watch at this step
Baseline
row count + result
Tip: use ← → to move between steps

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

CTEs in the same query
Best for: One report with nested logic

Strengths: Top-down reading; each step testable; no new objects.

Watch out: Steps can't be shared across queries.

Views for shared steps
Best for: Logic several queries repeat

Strengths: Defined once; reused everywhere.

Watch out: Another object to version and deploy.

Leave it nested
Best for: One or two short levels

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?
Interview tip: Emphasise the safety net: small steps and a two-way EXCEPT ALL check. Interviewers care that you won't break a report people rely on.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Chaining Multiple CTEs for Modular Data Pipelines
Next topic
CTE Optimization Fences (MATERIALIZED vs NOT MATERIALIZED)