Sub topic 2
Making sure the recursion stops
This chapter assumes you know SELECT, WHERE, JOIN, and basic CTEs. It also assumes you have seen the anchor and recursive members of a WITH RECURSIVE query. The examples use PostgreSQL syntax unless noted.
A recursive query repeats its recursive member until that member returns no new rows. If the data loops back on itself, or the join matches the same rows forever, the query never stops. You prevent this with a stop condition in the recursive member.
Making sure the recursion stops
The simplest guard is a depth limit. Add a counter to each row and stop adding rows once it reaches a set value.
WITH RECURSIVE counter AS (
SELECT 1 AS n
UNION ALL
SELECT n + 1 FROM counter WHERE n < 5
)
SELECT n FROM counter;The WHERE n < 5 clause filters the recursive step. When n reaches 5, that step returns no rows, and the query ends.
> Keep the stop condition in the recursive member, not in the outer query. An outer WHERE runs after the recursion finishes, so the recursion may already have run forever.
Walking an org chart
An org chart is a parent-child hierarchy. Each employee has a manager_id that points to another employee's id. The top manager has a NULL manager. The following query starts at the top and walks down, with a depth limit of 10 as a safety net.
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 e
JOIN org o ON e.manager_id = o.id
WHERE o.depth < 10
)
SELECT id, name, depth
FROM org
ORDER BY depth, name;Tracking depth and path through the tree
The depth counter shows how far each row sits from the top. A path array records the IDs visited on the way down. Checking the path before adding a row stops the query from revisiting a node, so a cycle in the data cannot cause endless recursion.
WITH RECURSIVE org AS (
SELECT id, name, ARRAY[id] AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, o.path || e.id
FROM employees e
JOIN org o ON e.manager_id = o.id
WHERE NOT (e.id = ANY(o.path))
)
SELECT name, cardinality(path) - 1 AS depth, path
FROM org;The cardinality(path) - 1 expression gives depth, because the top row's path holds one ID and depth starts at zero.
Exercise:
Exercise
Your employees table contains a cycle, where employee 4 has manager 7 and employee 7 has manager 4. Which guard stops the query, and why does a depth limit alone also work?
Show answer
The path check (WHERE NOT (e.id = ANY(o.path))) stops the query because it refuses any row whose ID was already visited. A depth limit also stops it, because the counter eventually reaches the limit and the recursive step returns no rows. The path check stops the cycle at the first repeat, while the depth limit only caps the length of the loop.