Interview's MateData Engineer
Interview's Mate

Data Engineer

SQL · Spark · Lakehouse · Streaming

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
Data Engineer topics
Lesson 24/ 160
02. Advanced SQL & Relational Databases

Common Table Expressions (CTEs) & Recursive CTEs

Structure readable SQL with CTEs and walk hierarchies or graphs with recursive CTEs.

IntermediateCTE · WITH · Recursive3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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 WITH and 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 EXPLAIN before adding MATERIALIZED or refactoring into inline SQL.

Visual diagram

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

Common Table Expressions & Recursive CTEs in one concrete design

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.

Key takeaway: 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

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.

Key takeaway: 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.

How it works, step by step

Step 1 of 4
CTE

1. 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.

seed the first stable result rows
Key numbers at this step
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 WITH and 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 EXPLAIN before adding MATERIALIZED or refactoring into inline SQL.

CTE / WITH / Recursive - roles, limits, and operating cost

CTE
Best for: A named relation scoped to one statement, introduced by 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.

WITH
Best for: The SQL keyword list that can also wrap data-modifying substatements in supporting databases.

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.

Recursive
Best for: A union-based fixed-point expansion with an anchor term and recursive term, subject to cycle and depth risks.

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 WITH and 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?
Interview tip: Lead with the data path and failure boundary: 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. Then make the answer operational: 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.

Knowledge check

Loading quiz

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.

Open Data Engineer Q&A →Machine Learning Q&A
Previous topic
Complex Joins (INNER, LEFT, FULL, CROSS, LATERAL)
Next topic
Window Functions (ROW_NUMBER, RANK, DENSE_RANK, NTILE)