Sub topic 13
Beyond One Level: Recursive CTEs
Assume you know SELECT, INNER JOIN, LEFT JOIN, primary and foreign keys, NULL, and basic aggregate functions. This chapter uses the employees table from the earlier examples:
ididentifies an employee.namestores the employee's name.manager_idpoints to another employee'sid.- A
NULLmanager means the employee is at the top of the hierarchy.
A self join can find one employee's manager. However, a fixed chain of self joins becomes awkward when you need every level:
SELECT e.name AS employee,
m.name AS manager,
d.name AS manager_of_manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
LEFT JOIN employees d ON m.manager_id = d.id;This query handles only two levels above each employee. Adding another level requires another join. A recursive common table expression, or recursive CTE, repeats the relationship until there are no more matching rows.
The two parts of a recursive CTE
A recursive CTE has an anchor query and a recursive query.
- The anchor query selects the starting rows.
- The recursive query finds the next rows from the results already found.
UNION ALLcombines the two parts.- A final query reads the complete result.
For an employee hierarchy, start with top-level employees. Then repeatedly find employees whose manager_id matches an employee already in the result.
WITH RECURSIVE chain AS (
-- Anchor: begin with employees who have no manager.
SELECT
id,
name,
manager_id,
0 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- Recursive part: find direct reports of known employees.
SELECT
e.id,
e.name,
e.manager_id,
c.depth + 1
FROM employees AS e
INNER JOIN chain AS c
ON e.manager_id = c.id
)
SELECT
name,
depth
FROM chain
ORDER BY depth, name;The depth column shows the distance from the top of the hierarchy. A top-level employee has depth 0. Their direct reports have depth 1, and so on.
With the sample data, the result is conceptually:
| name | depth |
|---|---|
| Ava | 0 |
| Ben | 1 |
| Chen | 1 |
| Dana | 2 |
The recursive query stops when the recursive part finds no new employees.
Common errors and database differences
The recursive part must return the same number of columns as the anchor, with compatible data types. If the anchor returns id, name, manager_id, and depth, the recursive query must return those four values in the same order.
Use UNION ALL unless you have a specific reason to remove duplicates. UNION performs duplicate elimination at each step and can add unnecessary work. More importantly, duplicate data may indicate a problem in the hierarchy that should be investigated rather than hidden.
A cycle can cause recursion to continue indefinitely or until the database's recursion limit is reached. For example, if Ava eventually points back to herself through manager_id, the query has no natural endpoint. Production queries may track visited IDs or use a database-specific cycle-detection feature.
Syntax differs slightly between database systems. PostgreSQL and SQLite use WITH RECURSIVE. SQL Server uses WITH without the RECURSIVE keyword and often adds an OPTION (MAXRECURSION ...) clause. Check your database documentation before moving this query between systems.
Exercise
What does the anchor query select in the employee hierarchy example, and why is depth set to 0 there?
Show answer
It selects employees whose manager_id is NULL because they are the hierarchy roots. Their depth is 0 because no parent relationship has been followed yet.