Sub topic 13
Beyond one level: recursive CTEs
This chapter assumes you can write an INNER JOIN and a LEFT JOIN, that you know how a self join uses aliases, and that you have the employees table from earlier chapters. Here is that table:
| id | name | manager_id |
|---|---|---|
| 1 | Ava | NULL |
| 2 | Ben | 1 |
| 3 | Chen | 1 |
| 4 | Dana | 2 |
Where chained self joins stop working
A self join follows one link in the hierarchy. To see an employee's manager, you join employees to itself once. To also see the manager's manager, you add a second join:
SELECT e.name AS employee,
m.name AS manager,
gm.name AS grand_manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
LEFT JOIN employees gm ON m.manager_id = gm.id
ORDER BY e.id;The result has four rows. Ava has no manager and no grand manager. Ben and Chen have Ava as manager and a NULL grand manager. Dana has Ben as manager and Ava as grand manager.
This query has two limits:
- Fixed depth. The query covers exactly two levels. If the company gains a fifth layer, you must edit the query and add another join.
- Unknown depth. Questions such as "list everyone below Ava" or "how deep is the tree?" cannot be written with a fixed number of joins.
A recursive common table expression (CTE) removes both limits. A CTE is a named query defined with WITH that you can use in the statement that follows. A recursive CTE is a CTE that refers to its own name, so it can repeat a step until no new rows appear.
Anatomy of a recursive CTE
A recursive CTE has two parts joined by UNION ALL:
- The anchor member runs once. It produces the starting rows, such as the top of the hierarchy.
- The recursive member joins the CTE's own name to the base table. It runs again and again, and each pass uses only the rows produced by the previous pass.
Here is the example from the plan:
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employees e
INNER JOIN chain c ON e.manager_id = c.id
)
SELECT name, depth
FROM chain
ORDER BY depth, name;The result:
| name | depth |
|---|---|
| Ava | 0 |
| Ben | 1 |
| Chen | 1 |
| Dana | 2 |
The recursive member is an ordinary self join. The alias e is the employee, and c is the manager row that the previous pass found. The join condition e.manager_id = c.id is the same parent-child condition you used before. The only new thing is that the "parent" side is the result built so far.
How the engine evaluates it
The database does not run the recursive member against the whole result each time. It feeds the member only the rows added in the last pass, and it stops when a pass returns no rows.
The sample table takes these passes:
- The anchor returns Ava at depth 0.
- Pass one finds employees whose
manager_idis 1. That returns Ben and Chen at depth 1. - Pass two finds employees whose
manager_idis 2 or 3. That returns Dana at depth 2. - Pass three finds employees whose
manager_idis 4. Nobody matches, so the recursion ends.
The outer SELECT then reads the union of all passes.
Dialect differences
The idea is the same everywhere, but the syntax varies:
| Database | Keyword and notes |
|---|---|
| PostgreSQL, MySQL 8.0+, SQLite, MariaDB | `WITH RECURSIVE` |
| SQL Server | `WITH` only, with no `RECURSIVE` keyword |
| Oracle | `WITH` only, and you can name the column list after the CTE name |
String concatenation also differs. PostgreSQL and SQLite use ||. SQL Server uses +. MySQL uses CONCAT(). The examples below use ||.
Useful variations
Build the path to each person
The recursive member can carry a value along, so each row can hold the whole chain from the top. This query records the reporting path:
WITH RECURSIVE chain AS (
SELECT id, name, CAST(name AS VARCHAR(200)) AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, c.path || ' > ' || e.name
FROM employees e
INNER JOIN chain c ON e.manager_id = c.id
)
SELECT name, path
FROM chain
ORDER BY path;The result has these paths: Ava, Ava > Ben, Ava > Ben > Dana, and Ava > Chen.
The CAST in the anchor matters. Many databases fix the column type from the anchor member. If the anchor column is a short VARCHAR(50), a longer path in a later pass can fail or be truncated. Casting to a wide type in the anchor avoids that.
Start from any employee, not only the top
The anchor decides where the walk starts. To list Ben and everyone below him, anchor on Ben's id:
WITH RECURSIVE team AS (
SELECT id, name, 0 AS depth
FROM employees
WHERE id = 2
UNION ALL
SELECT e.id, e.name, t.depth + 1
FROM employees e
INNER JOIN team t ON e.manager_id = t.id
)
SELECT name, depth
FROM team
ORDER BY depth, name;The result is Ben at depth 0 and Dana at depth 1.
Walk upward instead of downward
To find all of Dana's superiors, anchor on Dana and reverse the join condition. The next row to find is the one whose id equals the current row's manager_id:
WITH RECURSIVE bosses AS (
SELECT id, name, manager_id, 0 AS steps_up
FROM employees
WHERE id = 4
UNION ALL
SELECT e.id, e.name, e.manager_id, b.steps_up + 1
FROM employees e
INNER JOIN bosses b ON e.id = b.manager_id
)
SELECT name, steps_up
FROM bosses
ORDER BY steps_up;The result is Dana at 0, Ben at 1, and Ava at 2. The walk stops after Ava because her manager_id is NULL, and e.id = NULL matches nothing.
Failure mode: cycles
A hierarchy table does not stop you from storing a loop. Suppose a bad update makes Ava report to Dana:
UPDATE employees SET manager_id = 4 WHERE id = 1;Now Ava, Ben, and Dana form a loop. The earlier anchor (manager_id IS NULL) finds no starting row, so that query returns nothing. A query anchored on a person inside the loop would never run out of new rows and would repeat until the database stops it.
Defend against this in two ways:
- Put a depth limit in the recursive member. The condition stops the walk even if the data is bad:
WITH RECURSIVE team AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE id = 2
UNION ALL
SELECT e.id, e.name, e.manager_id, t.depth + 1
FROM employees e
INNER JOIN team t ON e.manager_id = t.id
WHERE t.depth < 20
)
SELECT name, depth
FROM team
ORDER BY depth, name;- Rely on engine limits as a backstop. SQL Server stops at 100 recursion levels by default, and you can change this with
OPTION (MAXRECURSION n). PostgreSQL 14 and later offer aCYCLEclause that marks rows that revisit a node. Other databases may run until they hit a resource limit, so do not depend on their behavior.
When to use a recursive CTE
| Situation | Better choice |
|---|---|
| You always need exactly one level, such as employee and direct manager | Plain self join |
| You need a fixed, small number of levels, such as two | Chained self joins |
| The depth is unknown or can change | Recursive CTE |
| You need all descendants or all ancestors of a node | Recursive CTE |
| You need depth, path, or a count of everyone under a manager | Recursive CTE |
| You query the same deep tree constantly and need the best speed | Consider storing a path or closure table |
Chained self joins also have a cost you can see in the query text. Each extra level adds another alias and another join, and each outer join keeps rows that have no match, which produces NULL columns you have to read. A recursive CTE keeps the query the same size at any depth.
Performance notes
Each pass runs a join between the base table and the working set. Without an index on manager_id, every pass scans the whole employees table. For a table with many rows, create the index:
CREATE INDEX idx_employees_manager_id ON employees (manager_id);Also keep the working set small. Anchor on the specific node you need, as in the "start from any employee" query, instead of building the entire tree and filtering afterward. Add WHERE filters inside the anchor or recursive member when you can, because filters in the outer SELECT run after all passes finish.
Summary
- A chain of self joins handles a fixed number of levels. A recursive CTE handles any depth.
- A recursive CTE has an anchor member, a recursive member, and a
UNION ALLbetween them. It stops when a pass returns no new rows. - The recursive member is a self join whose parent side is the CTE itself.
- You can carry a depth, a path, or other values from one pass to the next.
- Guard against cycles with a depth condition, and index the parent column.
Exercise
Using the sample employees table, write a recursive CTE that lists every employee who reports to Ava directly or indirectly, with a column levels_below_ava. Ava should not appear in the result. What rows should come back?
Show answer
Anchor on Ava's direct reports and count them as level 1, then add a recursive member: WITH RECURSIVE belowava AS ( SELECT id, name, 1 AS levelsbelowava FROM employees WHERE managerid = 1 UNION ALL SELECT e.id, e.name, b.levelsbelowava + 1 FROM employees e INNER JOIN belowava b ON e.managerid = b.id ) SELECT name, levelsbelowava FROM belowava ORDER BY levelsbelow_ava, name; The result is Ben at 1, Chen at 1, and Dana at 2. Ava is missing because the anchor starts from her reports, not from her.
Exercise
A recursive CTE runs for a very long time on a table that you suspect contains a loop. Name two changes that make the query stop safely.
Show answer
Add a depth condition to the recursive member, for example WHERE t.depth < 20, so the walk ends even when the data loops. Then fix the bad rows, or use an engine feature such as SQL Server's MAXRECURSION option or PostgreSQL 14's CYCLE clause to detect the repeat.