Common Table Expressions (CTEs) & Recursive CTEs
Structure readable SQL with CTEs and walk hierarchies or graphs with recursive CTEs.
In plain words
Seed the first stable result rows. Next, expand from newly available rows. Finally, join, aggregate, and materialize only if measured.
Think of it like…
A CTE names an ingredient bowl for a readable recipe; a recursive CTE is the same cook repeatedly handing each newly chopped batch to the next step until none remains.
Where you’ve seen it
WITH RECURSIVE paths(node, depth) AS (SELECT root,0 UNION ALL SELECT child,depth+1 FROM tree JOIN paths USING (node) WHERE depth < 20) SELECT * FROM paths; bounds traversal.
Words you’ll hear
- CTE
- A named relation scoped to one statement, introduced by
WITHand referenced later in that statement. - WITH
- The SQL keyword list that can also wrap data-modifying substatements in supporting databases.
- Recursive
- A union-based fixed-point expansion with an anchor term and recursive term, subject to cycle and depth risks.
- Operational boundary
- Recursive CTEs without a depth limit or visited-key guard can loop through cycles, and assuming a CTE is always materialized is optimizer-specific and historically produced poor SQL patterns. Use CTEs to expose pipeline stages, add a depth or maximum-step column, carry a visited path for cyclic graphs, and inspect
EXPLAINbefore addingMATERIALIZEDor refactoring into inline SQL.
Visual diagram
Theory & deep dive
CTE: the working mechanism
A common table expression gives a named query a local scope, and a recursive CTE repeatedly joins newly generated rows to a non-recursive anchor until it produces no more results.
Seed the first stable result rows. Expand from newly available rows, then set a depth or visited-state guard; this exposes the state governed by Recursive.
WITH RECURSIVE paths(node, depth) AS (SELECT root,0 UNION ALL SELECT child,depth+1 FROM tree JOIN paths USING (node) WHERE depth < 20) SELECT * FROM paths; bounds traversal.
Common Table Expressions & Recursive CTEs: failure mode and production response
Recursive CTEs without a depth limit or visited-key guard can loop through cycles, and assuming a CTE is always materialized is optimizer-specific and historically produced poor SQL patterns.
Use CTEs to expose pipeline stages, add a depth or maximum-step column, carry a visited path for cyclic graphs, and inspect EXPLAIN before adding MATERIALIZED or refactoring into inline SQL. Track Depth limit as "explicit maximum for a graph or hierarchy", and make Visited path visible to the dataset owner.
EXPLAIN before adding MATERIALIZED or refactoring into inline SQL.How it works, step by step
Step 1 of 41. Anchor
Seed the first stable result rows. A common table expression gives a named query a local scope, and a recursive CTE repeatedly joins newly generated rows to a non-recursive anchor until it produces no more results.
- Depth limit
- explicit maximum for a graph or hierarchy
- WITH
- The SQL keyword list that can also wrap data-modifying substatements in supporting databases.
When to use it & trade-offs
What it is
A common table expression gives a named query a local scope, and a recursive CTE repeatedly joins newly generated rows to a non-recursive anchor until it produces no more results. WITH RECURSIVE paths(node, depth) AS (SELECT root,0 UNION ALL SELECT child,depth+1 FROM tree JOIN paths USING (node) WHERE depth < 20) SELECT * FROM paths; bounds traversal.
Why it matters: Recursive CTEs without a depth limit or visited-key guard can loop through cycles, and assuming a CTE is always materialized is optimizer-specific and historically produced poor SQL patterns. Use CTEs to expose pipeline stages, add a depth or maximum-step column, carry a visited path for cyclic graphs, and inspect EXPLAIN before adding MATERIALIZED or refactoring into inline SQL.
When to reach for it
- Structure readable SQL with CTEs and walk hierarchies or graphs with recursive CTEs.
- Choose CTE because it provides this capability: A named relation scoped to one statement, introduced by
WITHand referenced later in that statement. - Keep evidence for Depth limit at "explicit maximum for a graph or hierarchy" so the last production stage-Consume - join, aggregate, and materialize only if measured-remains testable.
When to avoid or be careful
- Recursive CTEs without a depth limit or visited-key guard can loop through cycles, and assuming a CTE is always materialized is optimizer-specific and historically produced poor SQL patterns.
- Do not conflate WITH with CTE. The second concept contributes different behavior: The SQL keyword list that can also wrap data-modifying substatements in supporting databases.
- Release only after this guardrail is in place: Use CTEs to expose pipeline stages, add a depth or maximum-step column, carry a visited path for cyclic graphs, and inspect
EXPLAINbefore addingMATERIALIZEDor refactoring into inline SQL.
CTE / WITH / Recursive - roles, limits, and operating cost
WITH and referenced later in that statement.Strengths: A named relation scoped to one statement, introduced by WITH and referenced later in that statement. A common table expression gives a named query a local scope, and a recursive CTE repeatedly joins newly generated rows to a non-recursive anchor until it produces no more results.
Watch out: Recursive CTEs without a depth limit or visited-key guard can loop through cycles, and assuming a CTE is always materialized is optimizer-specific and historically produced poor SQL patterns.
Strengths: The SQL keyword list that can also wrap data-modifying substatements in supporting databases. In this workflow it supports: Terminate - set a depth or visited-state guard.
Watch out: The operating cost is real: prevents revisiting cyclic identifiers.
Strengths: A union-based fixed-point expansion with an anchor term and recursive term, subject to cycle and depth risks. Its output can be checked with EXPLAIN materialization.
Watch out: Operating guardrail: Use CTEs to expose pipeline stages, add a depth or maximum-step column, carry a visited path for cyclic graphs, and inspect EXPLAIN before adding MATERIALIZED or refactoring into inline SQL.
Interview signals & numbers to know
When this topic comes up
- “Where is the failure boundary for CTE, and how would Depth limit reveal it?”
- “Why is WITH distinct from this behavior: a union-based fixed-point expansion with an anchor term and recursive term, subject to cycle and depth risks?”
- Production clue: Recursive CTEs without a depth limit or visited-key guard can loop through cycles, and assuming a CTE is always materialized is optimizer-specific and historically produced poor SQL patterns.
- Design probe: Use CTEs to expose pipeline stages, add a depth or maximum-step column, carry a visited path for cyclic graphs, and inspect EXPLAIN before adding MATERIALIZED or refactoring into inline SQL.
Benchmarks & rules of thumb
- Depth limit
- explicit maximum for a graph or hierarchy
- Visited path
- prevents revisiting cyclic identifiers
- EXPLAIN materialization
- check optimizer behavior rather than assuming a CTE barrier
Common mistakes & follow-ups
Common interview mistakes
- Recursive CTEs without a depth limit or visited-key guard can loop through cycles, and assuming a CTE is always materialized is optimizer-specific and historically produced poor SQL patterns.
- Reporting success from a job exit code without checking Depth limit and Visited path.
- Treating this example as complete without replay, rollback, or access boundaries:
WITH RECURSIVE paths(node, depth) AS (SELECT root,0 UNION ALL SELECT child,depth+1 FROM tree JOIN paths USING (node) WHERE depth < 20) SELECT * FROM paths;bounds traversal.
Likely interviewer follow-ups
- How would you prove this contract instead of only checking that the command ran: A named relation scoped to one statement, introduced by
WITHand referenced later in that statement. - What does the recovery plan do when this occurs? Recursive CTEs without a depth limit or visited-key guard can loop through cycles, and assuming a CTE is always materialized is optimizer-specific and historically produced poor SQL patterns.
- When is CTE insufficient for Visited path, and what does adding WITH cost in Depth limit?
EXPLAIN before adding MATERIALIZED or refactoring into inline SQL.Knowledge check
Put it into practice
Practice related interview Q&A
Apply Common Table Expressions (CTEs) & Recursive CTEs with data engineer interview Q&A and hands-on practice.