skip to content

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.

team.sqlthe anchor
  1. 1WITH RECURSIVE team AS (
  2. 2 SELECT id, name, title, 0 AS depth
  3. 3 FROM employees
  4. 4 WHERE id = 14
  5. 5 UNION ALL
  6. 6 SELECT e.id, e.name, e.title, t.depth + 1
  7. 7 FROM employees AS e
  8. 8 JOIN team AS t ON e.manager_id = t.id
  9. 9)
  10. 10SELECT id, name, title, depth FROM team ORDER BY depth, id;
working table: what the anchor found1 row
the working table
idnametitledepth
14Ama Rossimanager0
the result so far1 of 13
the result so far
idnametitledepth
14Ama Rossimanager0

the anchor runs once: Ama Rossi, manager, employee 14. she is the whole working table, and the first row of the result.

step 1/4
real output, postgres 18.6 (PGlite 0.5.12) · recursive-ctes
step through the iterations. the working table is what the last round found, and the only thing the next round joins against. the result is every working table stacked up. the fourth round finds nobody, and that's the stop.

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

sqldb=org
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;
output, from postgres 18.6
SELECT 13
idint4nametexttitletextdepthint4
14Ama Rossimanager0
41Olivia Nguyenlead1
42Ananya Smithlead1
43Lucas Novaklead1
122Diego Wongassociate2
123Jonas Petrovassociate2
124Emma Duboisassociate2
125Mei Nguyenassociate2
126Clara Garciaassociate2
127Valentina Haddadassociate2
128Ama Haddadassociate2
129Ivan Hansenassociate2
130Ivan Ahmedassociate2
(13 rows)

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 team exactly once, and that team means "the working table", the rows from the previous round, never the whole result so far.
  • the outer query reads team like 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.

predict the output
sql
-- 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 6

run it and count:

sqldb=org
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;
output, from postgres 18.6
SELECT 4
idint4nametexttitletext
1Fatima Lopezceo
2Olivia Lopezvp
5Rahul Singhdirector
14Ama Rossimanager
(4 rows)

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:

SEARCH =
query.sql
  1. 1WITH RECURSIVE team AS (
  2. 2 SELECT id, name, 0 AS depth
  3. 3 FROM employees
  4. 4 WHERE id = 14
  5. 5 UNION ALL
  6. 6 SELECT e.id, e.name, t.depth + 1
  7. 7 FROM employees AS e
  8. 8 JOIN team AS t ON e.manager_id = t.id
  9. 9) SEARCH BREADTH FIRST BY id SET ord
  10. 10SELECT id, name, depth, ord FROM team ORDER BY ord;
the result for BREADTH FIRST
idint4nametextdepthint4ordrecord
14Ama Rossi0(0,14)
41Olivia Nguyen1(1,41)
42Ananya Smith1(1,42)
43Lucas Novak1(1,43)
122Diego Wong2(2,122)
123Jonas Petrov2(2,123)
124Emma Dubois2(2,124)
125Mei Nguyen2(2,125)
126Clara Garcia2(2,126)
127Valentina Haddad2(2,127)
128Ama Haddad2(2,128)
129Ivan Hansen2(2,129)
130Ivan Ahmed2(2,130)
(13 rows)

SEARCH BREADTH FIRST: a level at a time, like the iterations ran. ord is (depth, id) under the hood.

real output, postgres 18.6 (PGlite 0.5.12) · recursive-ctes
switch the search. 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
Ama Rossi's team, printed in the depth-first order above. click a name to fold it.

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:

sqldb=school
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;
output, from postgres 18.6
SELECT 6
codetextreachedint8
CS1011
CS2011
CS3011
MATH1012
MATH2011
MATH3011
(6 rows)

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:

sqldb=school
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;
output, from postgres 18.6
SELECT 6
codetext
CS101
CS201
CS301
MATH101
MATH201
MATH301
(6 rows)

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:

sqldb=org · session loop
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;
output, from postgres 18.6
#1 · SELECT 4
#2 · UPDATE 1
#3 · SELECT 4
idint4nametextmanager_idint4
1Fatima Lopez14
2Olivia Lopez1
5Rahul Singh2
14Ama Rossi5
(4 rows)

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:

sqldb=org · session loop
continues session loop (1 earlier block run first)
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;
output, from postgres 18.6
SELECT 10
idint4nametextstepsint4
14Ama Rossi0
5Rahul Singh1
2Olivia Lopez2
1Fatima Lopez3
14Ama Rossi4
5Rahul Singh5
2Olivia Lopez6
1Fatima Lopez7
14Ama Rossi8
5Rahul Singh9
(10 rows)

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:

sqldb=org · session loop
continues session loop (2 earlier blocks run first)
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;
output, from postgres 18.6
SELECT 5
idint4nametextloopedboolpath_record
14Ama Rossif{(14)}
5Rahul Singhf{(14),(5)}
2Olivia Lopezf{(14),(5),(2)}
1Fatima Lopezf{(14),(5),(2),(1)}
14Ama Rossit{(14),(5),(2),(1),(14)}
(5 rows)

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.

sqldb=org
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;
output, from postgres 18.6
EXPLAIN
CTE Scan on team CTE team -> Recursive Union -> Index Only Scan using employees_pkey on employees Index Cond: (id = 14) -> Hash Join Hash Cond: (e.manager_id = t.id) -> Seq Scan on employees e -> Hash -> WorkTable Scan on team t

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.