Tutorial

Nested Query to CTE in 4 Steps

Turn a 3-level nested subquery into a readable CTE interviewers can maintain at 2am: a 4-step refactor worksheet with before-and-after SQL code.

Anuj SainiSep 30, 20261 min read

Before

sql
SELECT a.x FROM
  (SELECT b.x FROM
    (SELECT x, y FROM t WHERE y > 0) b
   JOIN u ON b.id = u.id) a
WHERE a.x > 10

Aliases a, b, c. The interviewer stopped reading at line 12.

After

sql
WITH filtered AS (
  SELECT x, id FROM t WHERE y > 0
),
joined AS (
  SELECT f.x FROM filtered f JOIN u ON f.id = u.id
)
SELECT x FROM joined WHERE x > 10;

The 4 steps

  1. Name each level by what it IS, not a/b/c.
  2. One CTE per business step: filter first, aggregate second, join last.
  3. Keep the final SELECT flat and obvious.
  4. Test each CTE standalone — debugging becomes binary search.

Interviewers grade "could I maintain this at 2am," not cleverness. Practice refactors at Topfolio Practice.

Related: What Is Sql · Sql 30 Interview Questions Practice

Frequently Asked Questions

Are CTEs faster than subqueries?

Not necessarily — readability is the point. CTEs let you test each step standalone, which is how you debug fast in interviews and on the job.

When should I still use a subquery?

For single-use, one-level filters. Past two nesting levels, a CTE is almost always clearer.

Will a CTE make my query faster?

Not necessarily — the win is readability and standalone testability of each step, which is what interviewers grade.

Anuj Saini

Written by

Anuj SainiFounder & Lead Instructor

Founder at Topfolio with 6+ years in data & analytics across JPMC, Ultrahuman, and high-growth startups. Sat on hiring panels, reviewed 500+ resumes, and writes practical SQL & data guides.