Learn SQL
-- subqueries.recursive_cte

Recursive CTEs in SQL

Walk hierarchies and graphs with a query that calls itself

--concept

WITH RECURSIVE lets a CTE reference itself, turning SQL into a loop. An anchor query seeds the result, the recursive query repeatedly extends it — each pass seeing the previous pass’s rows — until nothing new appears. Org-chart reporting chains, bill-of-materials explosions and graph reachability all collapse from application loops into one declarative query.

--how it works
1

Anchor + recursive half

WITH RECURSIVE t AS ( anchor UNION ALL recursive ) — the anchor seeds rows; the recursive half references t itself.

2

The anchor runs once

Its rows form the first working set and land in the output immediately.

3

Each pass extends the set

The recursive SELECT reads the previous pass’s rows only, joins or transforms them, and queues its output as the next working set.

4

Iteration ends when a pass is empty

No new rows → the loop terminates; the result is the UNION (or UNION ALL) of every pass.

5

Guard against cycles

Carry a depth/visited column and cap or filter it — a cyclic graph (an employee as their own manager) would otherwise loop forever.

--visualization
ANCHOR — runs onceSELECT 5RECURSIVE STEPSELECT n−1 WHERE n > 1each pass feeds the nextpasses → valuespass 05pass 14pass 23pass 32pass 41TERMINATIONWHERE n > 1loop runs while rows appearUNION ALL of passes…5 rows — one per pass
anchor (seed) recursive step + emitted rows
Stage 1 / 7
Anchor query runs once: SELECT 5 — the working set starts with {5}.
--example
query.sql
1WITH RECURSIVE countdown (n) AS (
2 SELECT 5
3 UNION ALL
4 SELECT n - 1 FROM countdown WHERE n > 1
5)
6SELECT n FROM countdown;
Result
n
5
4
3
2
1

The anchor seeds n = 5. Pass 1 emits 4, pass 2 emits 3… each pass reading only the rows the previous pass produced. When n reaches 1 the WHERE blocks further rows, the loop ends, and the union of all passes is the countdown. Same mechanics, real data: employee → manager chains.

--variants

Countdown — the mechanics, bare

A minimal recursive CTE you can trace by hand.

query.sql
1WITH RECURSIVE countdown (n) AS (
2 SELECT 5
3 UNION ALL
4 SELECT n - 1 FROM countdown WHERE n > 1
5)
6SELECT n FROM countdown;
Result
n
5
4
3
2
1
1Anchor: 5. Pass 1 reads 5 → emits 4. Pass 2 reads 4 → emits 3…
2When n = 1 the WHERE stops the recursion; a pass returning zero rows ends the loop.
3Every pass sees only the previous pass’s rows — that working-set discipline is the whole model.

Management chain of one employee

The hierarchy use-case: walk up the org chart.

query.sql
1WITH RECURSIVE chain AS (
2 SELECT id, name, manager_id, 0 AS depth, name AS path
3 FROM employees_x WHERE id = 6
4 UNION ALL
5 SELECT m.id, m.name, m.manager_id, c.depth + 1, c.path || ' → ' || m.name
6 FROM employees_x m JOIN chain c ON m.id = c.manager_id
7)
8SELECT path, depth FROM chain ORDER BY depth;
Result
pathdepth
Farid0
Cynthia → Farid1
Cynthia2
1Anchor: Farid (depth 0). Pass 1 finds his manager Cynthia (depth 1).
2Pass 2 looks for Cynthia’s manager — none in this data, so the loop ends.
3The path column accumulates the chain for display; depth both documents and guards the recursion.

Whole subtree below a node

Downward traversal — everyone under a manager.

query.sql
1WITH RECURSIVE subtree AS (
2 SELECT id, name FROM employees_x WHERE manager_id = 3
3 UNION ALL
4 SELECT e.id, e.name
5 FROM employees_x e JOIN subtree s ON e.manager_id = s.id
6)
7SELECT count(*) AS reports FROM subtree;
Result
reports
3
1Anchor: direct reports of Cynthia. Pass 1: their reports. Pass 2: none — done.
2The depth of recursion equals the org depth below the node — no schema knowledge needed upfront.
3The same shape explodes a bill-of-materials or a folder tree.

Cycle guard with a depth cap

Bad data must not become an infinite loop.

query.sql
1WITH RECURSIVE walk AS (
2 SELECT id, parent_id, 1 AS depth FROM nodes WHERE id = 1
3 UNION ALL
4 SELECT n.id, n.parent_id, w.depth + 1
5 FROM nodes n JOIN walk w ON n.parent_id = w.id
6 WHERE w.depth < 50
7)
8SELECT * FROM walk;
9-- depth < 50 caps pathological data
Result
guarantee
recursion bounded at depth 50 — terminates even with a parent loop
1The WHERE on the recursive half runs every pass — depth 50 hard-stops the walk.
2Some engines offer CYCLE clauses (Postgres 14+) or explicit cycle detection; the depth cap is the portable baseline.
3Pair it with a logged warning: a hit cap usually means the data needs cleaning, not the query.
--key facts
Two halvesanchor seed + recursive step, glued by UNION ALL (deduping UNION also works but costs a sort each pass)
Depth guardcarry a depth counter and cap it — the portable defence against cycles
Dialect noteSQL Server uses a semicolon before WITH; older MySQL needs WITH RECURSIVE spelled out
--use cases
Org charts, category trees, menu structures, folder hierarchies
Bill-of-materials explosion in manufacturing
Graph reachability: transitive closure of friendships or routes
Sequence generation (calendars, date spines) without a numbers table
--under the hood
UNION ALL avoids a dedup pass per iteration; UNION terminates on cycles automatically but pays for hashing every pass.
Depth is the memory bound — each pass’s working set is held; wide-and-deep traversals may need materialisation tweaks.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.