Recursive CTEs
Walk a tree such as an org chart with WITH RECURSIVE, see the working table fill round by round, and stop loops safely.
A CTE that uses itself
A recursive CTE refers to its own result. It has two parts joined by UNION ALL: a starting part that runs once, and a recursive part that runs again and again on the rows found in the previous round.
You write WITH RECURSIVE. The database keeps a working table with the rows of the latest round. It repeats the recursive part against that table until a round produces no new rows, then stops.
Trees and chains of any depth
Org charts, folders inside folders, category trees and comment replies all have a depth that nobody knows in advance. A normal join needs one join per level. A recursive CTE follows the chain however long it is.
Walk the org chart from the top
WITH RECURSIVE tree(id, name, depth) AS (
SELECT id, name, 0 FROM staff WHERE id = 1
UNION ALL
SELECT s.id, s.name, tree.depth + 1
FROM staff s JOIN tree ON s.manager_id = tree.id
)
SELECT * FROM tree;Round 0 finds Asha, the starting row, at depth 0. Round 1 finds the people who report to Asha: Ben and Chen, depth 1. Round 2 finds who reports to them: Dara and Eli, depth 2. Round 3 finds nobody, the working table is empty, and the query stops with 5 rows.
The classic first example is counting: SELECT 1 UNION ALL SELECT n + 1 FROM t WHERE n < 5 produces 1, 2, 3, 4, 5. The WHERE n < 5 is what stops it.
Run it one round at a time
Press Next round and watch the working table and the result grow. Then try the loop modes to see what happens with no guard and with CYCLE.
| idinteger | nametext | depthinteger |
|---|---|---|
| 1 | Asha | 0 |
| idinteger | nametext | depthinteger |
|---|---|---|
| 1 | Asha | 0 |
Round 0 runs the starting part once. Its rows become the working table. Press Next round to feed them into the recursive part.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A recursive CTE is a starting part plus a recursive part, joined by UNION ALL.
- Each round runs the recursive part on the rows of the previous round (the working table).
- It stops when a round finds no new rows.
- Data that loops makes the query run forever, so add a stop: a depth limit or CYCLE.
Done with this concept?
Mark it complete to track your progress. No login needed.