Sub topic 5
Recursive CTEs: Anchor Member, Recursive Member, and `UNION ALL`
Assume you know SELECT, joins, WHERE, and basic CTE syntax. You should also understand that a table can contain rows that point to other rows, such as employees pointing to managers.
A recursive common table expression (CTE) is a CTE that refers to itself. It is useful when the number of steps is unknown, such as walking an organization chart, category tree, or graph.
The two parts of a recursive CTE
A recursive CTE has two query parts:
- The anchor member returns the starting rows.
- The recursive member finds the next rows by using results from the previous step.
The two parts are combined with UNION ALL. The database evaluates the anchor member first. It then evaluates the recursive member repeatedly until that member returns no new rows or another condition stops it.
This example generates the numbers from 1 through 5:
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1
FROM numbers
WHERE n < 5
)
SELECT n
FROM numbers;The anchor member is SELECT 1. It produces the first row. The recursive member adds 1 to the current value. Its WHERE condition prevents another row after 5.
The result is:
| n |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
The recursive member must eventually stop producing rows. Without a stopping rule, the query may run until the database reaches a recursion limit, consumes too many resources, or fails.
Traversing a hierarchy
Consider an employees table with these columns:
| Column | Meaning |
|---|---|
| `id` | The employee's identifier |
| `name` | The employee's name |
| `manager_id` | The identifier of the employee's manager |
A top-level employee has a NULL manager_id. Each recursive step joins employees to the rows found in the previous step.
WITH RECURSIVE org 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,
o.depth + 1
FROM employees AS e
JOIN org AS o
ON e.manager_id = o.id
)
SELECT id, name, depth
FROM org
ORDER BY depth, name;The anchor member finds the top-level employees and assigns them depth 0. The recursive member finds direct reports of those employees and assigns them depth 1. On the next round, it finds reports of those reports and assigns them depth 2.
The depth column is not required for recursion. It records how many relationships separate a row from the starting row. You can use it to indent a report, limit traversal, or identify unusually deep data.
`UNION ALL` and recursion control
UNION ALL keeps every row produced by each round. This is usually the expected behavior because each path or level can matter.
Plain UNION removes duplicate rows. It can sometimes prevent repeated results, but it is not a complete cycle-protection strategy. Two different paths can still produce useful or repeated-looking rows, and duplicate removal can hide data problems.
A depth limit provides a simple safety guard:
WITH RECURSIVE org 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, o.depth + 1
FROM employees AS e
JOIN org AS o ON e.manager_id = o.id
WHERE o.depth < 10
)
SELECT id, name, depth
FROM org;This query never follows more than ten relationships. However, a depth limit can stop a valid hierarchy before it is complete. It is a safety limit, not proof that the data contains no cycle.
For a graph, track the identifiers already visited. PostgreSQL arrays provide one way to do this:
WITH RECURSIVE walk AS (
SELECT 1 AS id, ARRAY[1] AS path
UNION ALL
SELECT e.to_id, w.path || e.to_id
FROM walk AS w
JOIN edges AS e ON e.from_id = w.id
WHERE e.to_id <> ALL (w.path)
)
SELECT id, path
FROM walk;The condition skips an edge whose destination is already in the current path. That prevents the current traversal path from looping back to an earlier node.
A practical checklist
Before using a recursive CTE, check that:
- The anchor member has the correct starting rows.
- Both members return the same number of columns.
- Corresponding columns have compatible types.
- The recursive member moves toward a stopping condition.
- Cycles are impossible, limited by depth, or explicitly guarded.
- The expected database supports the syntax you use.
Exercise
In the numbers example, what happens if the recursive member is SELECT n + 1 FROM numbers with no WHERE condition?
Show answer
The recursive member keeps producing larger numbers without a termination condition. The query can run indefinitely or stop only when the database enforces a resource or recursion limit.