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 70/ 160
04. Subqueries & Common Table Expressions (CTEs)

Recursive CTEs Fundamentals (Anchor Member + Recursive Member)

Write recursive WITH queries using an anchor seed and recursive step.

AdvancedAnchor · Recursive · UNION ALL3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Start with some rows, then keep asking "who comes next?" and adding the answers, until there's nobody new.

Think of it like…

Tracing a family tree: start with one person (the anchor), find their children, then those children's children, and keep going until a generation has no children left.

Where you’ve seen it

Listing every employee in a VP's organisation, with their depth below the VP: start from the VP's row, then repeatedly join employees whose manager_id is in the rows found so far.

Words you’ll hear

Anchor member
The non-recursive query that produces the starting rows.
Recursive member
The query that references the CTE itself to produce the next level.
Termination
Recursion stops when the recursive member returns no rows.
Cycle
Data that loops back (A → B → A), which would recurse forever without protection.

Visual diagram

Loading interactive diagram

Theory & example queries

How a recursive CTE runs

The database runs the anchor once and puts its rows in a working set. It then runs the recursive member against just that working set, adds the new rows to the result, makes them the new working set, and repeats. When an iteration finds nothing, it stops and returns everything collected.

The recursive member must reference the CTE exactly once, typically in a join. PostgreSQL and MySQL 8 need the RECURSIVE keyword (WITH RECURSIVE); SQL Server and Oracle use plain WITH.

Everyone under manager 10, with depthQuery 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.sql
1WITH RECURSIVE2  org AS (3    SELECT4      id,5      name,6      manager_id,7      0 AS depth8    FROM9      employees10    WHERE11      id = 1012    UNION ALL13    SELECT14      e.id,15      e.name,16      e.manager_id,17      org.depth + 118    FROM19      employees e20      JOIN org ON e.manager_id = org.id21  )22SELECT23  *24FROM25  org26ORDER BY27  depth;
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/27
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative hierarchy rows4 sample rows
Representative hierarchy rows
idnamemanager_iddepth
10Asha RaoNULL0
24Ravi Shah101
31Mira Sen101
47Kunal Das242

Note: The sample assumes this four-person subtree and no cycles. Rows at the same depth do not have a guaranteed internal order because only depth is in the final ORDER BY.

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

Key takeaway: Anchor once, then repeat the recursive member on the newest rows until it's empty.

Stopping safely

If the data has a cycle (a bad update makes A manage B and B manage A), the recursion never ends. Protect against it by carrying the path as an array and skipping ids already in it, by adding a depth limit (WHERE depth < 20), or with PostgreSQL 14's CYCLE id SET is_cycle USING path clause.

Engines also have safety limits: SQL Server stops at 100 levels by default (change it with OPTION (MAXRECURSION n)), and MySQL at 1,000 (cte_max_recursion_depth). Using UNION instead of UNION ALL removes duplicate rows, which can stop some cycles, but it costs a deduplication step each iteration.

Generating a number or date seriesQuery 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.sql
1WITH RECURSIVE2  n AS (3    SELECT4      1 AS x5    UNION ALL6    SELECT7      x + 18    FROM9      n10    WHERE11      x < 1012  )13SELECT14  x15FROM16  n;
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/16
3OutputInspect the representative rows, affected-row count, plan, or command status.
First four generated rows4 sample rows
First four generated rows
x
1
2
3
4

Note: The complete recursive result contains 10 rows, from 1 through 10. Four rows are shown here as a compact representative sample.

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

The WHERE is what stops it.

Key takeaway: Always have a stopping condition: no new rows, a depth limit or cycle detection.

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 1Anchor member

Write the anchor

Select the starting rows, such as the manager you're starting from or the root categories, and include a depth column set to 0.

SQL at this step
1SELECT2  id,3  manager_id,4  0 AS depth5FROM6  employees7WHERE8  id = 10
What to watch at this step
Runs
once
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A recursive CTE builds a result by repeating a query on its own output. It has an anchor member (the starting rows), UNION ALL, and a recursive member that joins back to the CTE to find the next level. The database repeats the recursive member until it returns no new rows.

Why it matters: Hierarchies of unknown depth (org charts, category trees, folder structures, bill of materials) and graph walks can't be done with a fixed number of joins. Recursive CTEs are the standard SQL answer, and "list everyone under this manager" is a common interview question.

When to reach for it

  • Org charts: everyone under a manager, or the chain above an employee
  • Category trees and folder structures
  • Generating number or date sequences when generate_series isn't available

When to avoid or be careful

  • Recursive queries on data that can contain cycles, without a guard
  • UNION (not ALL) by habit, which adds a deduplication cost each iteration
  • Recursive CTEs for fixed one-level lookups, where a self join is enough

Recursive CTE vs self joins vs other models

Recursive CTE
Best for: Hierarchies and graphs of unknown depth

Strengths: Any depth in a single query, in standard SQL.

Watch out: Needs cycle protection; can be slow on very large graphs.

Fixed chain of self joins
Best for: A known, small number of levels (employee → manager → director)

Strengths: Simple and fast.

Watch out: Breaks as soon as the hierarchy gets one level deeper.

Materialised path / ltree / closure table
Best for: Read-heavy trees queried constantly

Strengths: Subtree queries without recursion.

Watch out: Extra data to maintain on every move or insert.

Interview signals & numbers to know

When this topic comes up

  • “Find all employees under this manager”
  • “Show the full category path”
  • parent_id columns of unknown depth
  • Bill of materials
  • “Generate a sequence of dates”

Benchmarks & rules of thumb

100 -
SQL Server's default MAXRECURSION
1,000 -
MySQL's default cte_max_recursion_depth
PostgreSQL 14 -
added the CYCLE and SEARCH clauses

Common mistakes & follow-ups

Common interview mistakes

  • Forgetting the stopping condition when generating a series, causing infinite recursion until the engine's limit.
  • Joining in the wrong direction (org.manager_id = e.id), which walks up the tree instead of down.
  • Running a recursive query on data with a cycle and no protection.

Likely interviewer follow-ups

  • How would you return the chain of managers above an employee, up to the CEO?
  • How do you detect and stop cycles in a recursive CTE?
  • How would you show each category's full path, like Electronics > Phones > Android?
Interview tip: Write it in three labelled parts (anchor, UNION ALL, recursive member) and mention the stopping condition and cycle protection. Interviewers check for both.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Recursive CTEs Fundamentals (Anchor Member + Recursive Member) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
CTE Optimization Fences (MATERIALIZED vs NOT MATERIALIZED)
Next topic
Traversing Organizational Charts & Category Trees with Recursive CTEs