Recursive CTEs Fundamentals (Anchor Member + Recursive Member)
Write recursive WITH queries using an anchor seed and recursive step.
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
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.
WITH RECURSIVE org AS ( SELECT id, name, manager_id, 0 AS depth FROM employees WHERE id = 10 UNION ALL SELECT e.id, e.name, e.manager_id, org.depth + 1 FROM employees e JOIN org ON e.manager_id = org.id )SELECT *FROM orgORDER BY depth;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative hierarchy rows4 sample rows
| id | name | manager_id | depth |
|---|---|---|---|
| 10 | Asha Rao | NULL | 0 |
| 24 | Ravi Shah | 10 | 1 |
| 31 | Mira Sen | 10 | 1 |
| 47 | Kunal Das | 24 | 2 |
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.
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.
WITH RECURSIVE n AS ( SELECT 1 AS x UNION ALL SELECT x + 1 FROM n WHERE x < 10 )SELECT xFROM n;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
First four generated rows4 sample 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.
The WHERE is what stops it.
Key takeaway: Always have a stopping condition: no new rows, a depth limit or cycle detection.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
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.
SELECT id, manager_id, 0 AS depthFROM employeesWHERE id = 10When 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
Strengths: Any depth in a single query, in standard SQL.
Watch out: Needs cycle protection; can be slow on very large graphs.
Strengths: Simple and fast.
Watch out: Breaks as soon as the hierarchy gets one level deeper.
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?
Knowledge check
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.