recursive CTEs
a query that feeds on its own output. walking an org chart, depth first or breadth first, with CYCLE for loops.
- address
- everything.analytics.recursive_ctes
- part
- part 4, windows, grouping and recursion
- chapter
- chapter 10 of 11
- reading time
- 9 min
a recursive CTE is WITH RECURSIVE name AS (anchor UNION ALL recursive part), where the recursive part refers to name itself. postgres runs the anchor once, then runs the recursive part over and over, each time against only the rows the last round found (the working table), and stops on the first round that finds nothing.
that's how SQL walks trees and graphs: org charts, prerequisites, routes. SEARCH picks depth-first or breadth-first order; CYCLE stops loops.
the picture
you know how "everyone under this manager" is easy one level down (a join) and two levels down (two joins), and impossible for "any number of levels" with plain joins, because you'd have to know the depth before you write the query? a recursive CTE writes the join once and lets postgres repeat it until it runs dry.
think of a phone tree. the manager calls her three leads. each lead calls their own reports. nobody calls back up, nobody calls twice, and when a round of calls reaches people with no one left to call, the tree is done. each round only involves the people who were just called (the working table), not everyone called so far.
- 1WITH RECURSIVE team AS (
- 2 SELECT id, name, title, 0 AS depth
- 3 FROM employees
- 4 WHERE id = 14
- 5 UNION ALL
- 6 SELECT e.id, e.name, e.title, t.depth + 1
- 7 FROM employees AS e
- 8 JOIN team AS t ON e.manager_id = t.id
- 9)
- 10SELECT id, name, title, depth FROM team ORDER BY depth, id;
| id | name | title | depth |
|---|---|---|---|
| 14 | Ama Rossi | manager | 0 |
| id | name | title | depth |
|---|---|---|---|
| 14 | Ama Rossi | manager | 0 |
the anchor runs once: Ama Rossi, manager, employee 14. she is the whole working table, and the first row of the result.
these are the leads from window frames, as it happens: Ama Rossi manages Olivia, Ananya and Lucas. the org dataset is a complete tree with three reports per manager, so the rounds go 1, 3, 9, and then nothing, because the associates manage nobody.
the shape
WITH RECURSIVE team AS (
SELECT id, name, title, 0 AS depth -- the anchor: where to start
FROM employees
WHERE id = 14
UNION ALL
SELECT e.id, e.name, e.title, t.depth + 1 -- the recursive part: one step further
FROM employees AS e
JOIN team AS t ON e.manager_id = t.id
)
SELECT id, name, title, depth
FROM team
ORDER BY depth, id;| idint4 | nametext | titletext | depthint4 |
|---|---|---|---|
| 14 | Ama Rossi | manager | 0 |
| 41 | Olivia Nguyen | lead | 1 |
| 42 | Ananya Smith | lead | 1 |
| 43 | Lucas Novak | lead | 1 |
| 122 | Diego Wong | associate | 2 |
| 123 | Jonas Petrov | associate | 2 |
| 124 | Emma Dubois | associate | 2 |
| 125 | Mei Nguyen | associate | 2 |
| 126 | Clara Garcia | associate | 2 |
| 127 | Valentina Haddad | associate | 2 |
| 128 | Ama Haddad | associate | 2 |
| 129 | Ivan Hansen | associate | 2 |
| 130 | Ivan Ahmed | associate | 2 |
three parts, and each has a job:
- the anchor (before UNION ALL) runs once. it can't mention
team. - the recursive part (after it) mentions
teamexactly once, and thatteammeans "the working table", the rows from the previous round, never the whole result so far. - the outer query reads
teamlike any table, after the loop has finished.
the depth column isn't required. it's just a counter you carry along, and it's handy: for ordering, for "only three levels down" (WHERE t.depth < 3 in the recursive part), and as a seatbelt against loops.
-- walk *up* from Ama Rossi (14) to the top
WITH RECURSIVE chain AS (
SELECT id, name, manager_id FROM employees WHERE id = 14
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees AS e JOIN chain AS c ON e.id = c.manager_id
)
SELECT name FROM chain;
-- 14 is a manager, level 3 of 6run it and count:
WITH RECURSIVE chain AS (
SELECT id, name, title, manager_id FROM employees WHERE id = 14
UNION ALL
SELECT e.id, e.name, e.title, e.manager_id
FROM employees AS e
JOIN chain AS c ON e.id = c.manager_id
)
SELECT id, name, title
FROM chain
ORDER BY id;| idint4 | nametext | titletext |
|---|---|---|
| 1 | Fatima Lopez | ceo |
| 2 | Olivia Lopez | vp |
| 5 | Rahul Singh | director |
| 14 | Ama Rossi | manager |
depth first or breadth first
the loop naturally produces rows a level at a time (breadth first), but nothing promises that order in the output. to get an order you can rely on, ask for one with SEARCH pg 14+, which adds a sort-key column you then ORDER BY:
- 1WITH RECURSIVE team AS (
- 2 SELECT id, name, 0 AS depth
- 3 FROM employees
- 4 WHERE id = 14
- 5 UNION ALL
- 6 SELECT e.id, e.name, t.depth + 1
- 7 FROM employees AS e
- 8 JOIN team AS t ON e.manager_id = t.id
- 9) SEARCH BREADTH FIRST BY id SET ord
- 10SELECT id, name, depth, ord FROM team ORDER BY ord;
| idint4 | nametext | depthint4 | ordrecord |
|---|---|---|---|
| 14 | Ama Rossi | 0 | (0,14) |
| 41 | Olivia Nguyen | 1 | (1,41) |
| 42 | Ananya Smith | 1 | (1,42) |
| 43 | Lucas Novak | 1 | (1,43) |
| 122 | Diego Wong | 2 | (2,122) |
| 123 | Jonas Petrov | 2 | (2,123) |
| 124 | Emma Dubois | 2 | (2,124) |
| 125 | Mei Nguyen | 2 | (2,125) |
| 126 | Clara Garcia | 2 | (2,126) |
| 127 | Valentina Haddad | 2 | (2,127) |
| 128 | Ama Haddad | 2 | (2,128) |
| 129 | Ivan Hansen | 2 | (2,129) |
| 130 | Ivan Ahmed | 2 | (2,130) |
SEARCH BREADTH FIRST: a level at a time, like the iterations ran. ord is (depth, id) under the hood.
BREADTH FIRST lists each level before the next, the way the iterations ran. DEPTH FIRST follows Olivia's branch to the bottom before Ananya's, which is the order an indented org chart is printed in.depth first is the one you want for drawing a tree, since every person comes right after their manager:
- manager, 14
- ├── lead, 41
- │ ├── Diego Wongassociate, 122
- │ ├── Jonas Petrovassociate, 123
- │ └── Emma Duboisassociate, 124
- ├── lead, 42
- │ ├── Mei Nguyenassociate, 125
- │ ├── Clara Garciaassociate, 126
- │ └── Valentina Haddadassociate, 127
- └── lead, 43
- ├── Ama Haddadassociate, 128
- ├── Ivan Hansenassociate, 129
- └── Ivan Ahmedassociate, 130
under the hood, the depth-first ord is the array of ids from the top down to the row ({(14),(41),(122)}), and sorting arrays element by element walks the tree. before postgres 14 you built that array by hand, and the release notes say as much: SEARCH and CYCLE do what existing syntax could, "much less conveniently".
UNION or UNION ALL
UNION ALL keeps every row the recursive part produces. plain UNION drops rows that are already in the result, before they become the next working table. on a tree it makes no difference. on a graph where two paths meet, it does. the school's prerequisites are a graph: Database Internals (CS401) needs CS301 and MATH301, and both of those lead to Calculus I:
WITH RECURSIVE needs AS (
SELECT requires_code AS code FROM prerequisites WHERE course_code = 'CS401'
UNION ALL
SELECT p.requires_code FROM prerequisites AS p JOIN needs AS n ON p.course_code = n.code
)
SELECT code, count(*) AS reached FROM needs GROUP BY code ORDER BY code;| codetext | reachedint8 |
|---|---|
| CS101 | 1 |
| CS201 | 1 |
| CS301 | 1 |
| MATH101 | 2 |
| MATH201 | 1 |
| MATH301 | 1 |
MATH101 is reached twice, once through MATH201 and once through MATH301. with UNION, the second arrival is a duplicate of a row already found, so it's dropped, and nothing downstream of it runs twice:
WITH RECURSIVE needs AS (
SELECT requires_code AS code FROM prerequisites WHERE course_code = 'CS401'
UNION
SELECT p.requires_code FROM prerequisites AS p JOIN needs AS n ON p.course_code = n.code
)
SELECT code FROM needs ORDER BY code;| codetext |
|---|
| CS101 |
| CS201 |
| CS301 |
| MATH101 |
| MATH201 |
| MATH301 |
six courses, each once. that dedup is also a loop breaker, but only while every column stays the same each time round. add a depth counter and no row is ever a duplicate again.
loops, and CYCLE
real data has loops that shouldn't be there. make one on purpose: a copy of four people from the top of the org, and a typo that makes the CEO report to Ama Rossi:
CREATE TEMP TABLE chart AS
SELECT id, name, manager_id FROM employees WHERE id IN (1, 2, 5, 14);
UPDATE chart SET manager_id = 14 WHERE id = 1;
SELECT id, name, manager_id FROM chart ORDER BY id;| idint4 | nametext | manager_idint4 |
|---|---|---|
| 1 | Fatima Lopez | 14 |
| 2 | Olivia Lopez | 1 |
| 5 | Rahul Singh | 2 |
| 14 | Ama Rossi | 5 |
walking up from Ama now goes 14 → 5 → 2 → 1 → 14 → ... forever. postgres has no built-in limit on recursion, so a query like that runs until something stops it (a statement_timeout, or you). a depth seatbelt shows the loop going round:
WITH RECURSIVE up AS (
SELECT id, name, manager_id, 0 AS steps FROM chart WHERE id = 14
UNION ALL
SELECT c.id, c.name, c.manager_id, u.steps + 1
FROM chart AS c JOIN up AS u ON c.id = u.manager_id
WHERE u.steps < 9
)
SELECT id, name, steps FROM up ORDER BY steps;| idint4 | nametext | stepsint4 |
|---|---|---|
| 14 | Ama Rossi | 0 |
| 5 | Rahul Singh | 1 |
| 2 | Olivia Lopez | 2 |
| 1 | Fatima Lopez | 3 |
| 14 | Ama Rossi | 4 |
| 5 | Rahul Singh | 5 |
| 2 | Olivia Lopez | 6 |
| 1 | Fatima Lopez | 7 |
| 14 | Ama Rossi | 8 |
| 5 | Rahul Singh | 9 |
CYCLE pg 14+ does it properly. it tracks the path, and when a row would revisit a value already on its path, it marks that row and doesn't recurse from it:
WITH RECURSIVE up AS (
SELECT id, name, manager_id FROM chart WHERE id = 14
UNION ALL
SELECT c.id, c.name, c.manager_id
FROM chart AS c JOIN up AS u ON c.id = u.manager_id
) CYCLE id SET looped USING path
SELECT id, name, looped, path FROM up ORDER BY path;| idint4 | nametext | loopedbool | path_record |
|---|---|---|---|
| 14 | Ama Rossi | f | {(14)} |
| 5 | Rahul Singh | f | {(14),(5)} |
| 2 | Olivia Lopez | f | {(14),(5),(2)} |
| 1 | Fatima Lopez | f | {(14),(5),(2),(1)} |
| 14 | Ama Rossi | t | {(14),(5),(2),(1),(14)} |
five rows. the fifth is Ama again, with looped = true and the path that got there: {(14),(5),(2),(1),(14)}. that's the row you want to find in a data-quality check, and the query ends on its own.
one level deeperwhat the executor actually does
the plan has a Recursive Union node with the anchor as its first child and the recursive part as its second, and a WorkTable Scan inside the recursive part reading the working table. each round writes its output to a fresh intermediate table, which becomes the next WorkTable. it's a loop in the executor, not recursion on a call stack, so depth costs nothing but rows. the manual's WITH queries page describes the same evaluation as numbered steps: run the recursive term with the working table substituted for the self-reference, and repeat for as long as the working table isn't empty.
EXPLAIN (COSTS OFF)
WITH RECURSIVE team AS (
SELECT id, 0 AS depth FROM employees WHERE id = 14
UNION ALL
SELECT e.id, t.depth + 1 FROM employees AS e JOIN team AS t ON e.manager_id = t.id
)
SELECT * FROM team;WITH and CTEs covers the non-recursive kind: naming a subquery, and when postgres inlines it. a recursive CTE is never inlined; it has to run its loop. and hierarchies as a design question (adjacency lists like manager_id, closure tables, ltree paths) are in hierarchies.
keylines
- WITH RECURSIVE: an anchor, UNION ALL, and a part that refers to the CTE itself.
- each round sees only the previous round's rows (the working table). an empty round stops it.
- the output order isn't promised: SEARCH BREADTH or DEPTH FIRST, then ORDER BY the column it sets.
- UNION drops repeats, which also stops loops, but only while every column repeats exactly.
- CYCLE marks the row that closes a loop and stops there. postgres has no recursion limit of its own.