Sub topic 6
Stopping Recursive SQL Queries Safely
Assume you know SELECT, joins, UNION ALL, and basic common table expressions (CTEs). This chapter focuses on recursive CTEs that walk sequences, trees, and graphs. The central rule is simple: every recursive query needs a clear stopping condition.
Why recursion needs a stopping rule
A recursive CTE has two parts:
- The anchor member produces the starting rows.
- The recursive member uses rows already found to produce more rows.
The database repeats the recursive member until it produces no new rows. If each round continues producing rows, the query can run for a very long time, consume resources, or fail because the database reaches a recursion limit.
This query generates 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 returns 1. Each recursive round adds 1. When n reaches 5, the WHERE n < 5 condition is false, so the recursive member returns no rows.
A recursive CTE is evaluated in rounds:
Termination conditions
The most common stopping rule compares a changing value with a fixed boundary. For dates, the recursive member can advance one day until it reaches an end date:
WITH RECURSIVE calendar(day) AS (
SELECT DATE '2026-01-01'
UNION ALL
SELECT day + INTERVAL '1 day'
FROM calendar
WHERE day < DATE '2026-01-07'
)
SELECT day
FROM calendar
ORDER BY day;The recursive expression must move toward termination. If the query adds one day but checks whether the date is greater than the end date, the condition may never become false.
A termination condition can also depend on a relationship. In an organization chart, recursion stops naturally when an employee has no direct reports:
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
)
SELECT id, name, depth
FROM org;Here, the join produces no rows when the current level has no children. However, malformed data containing a management cycle can prevent that assumption from being safe.
Depth limits as a safety guard
A depth column gives you a second control. It limits how far the query may descend, even if the data contains an unexpected cycle or an extremely deep hierarchy.
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;This query includes rows through depth 10. The condition is evaluated on the current row before creating the next level. A depth limit is useful as a maximum-work guard, but it can hide valid descendants below the limit. Treat the limit as a deliberate business rule or a defensive ceiling.
| Guard | Best use | Limitation |
|---|---|---|
| Changing-value condition | Sequences and date ranges | Must move toward the boundary |
| No-more-children condition | Trees and parent-child data | Does not protect against cycles |
| Depth limit | Maximum traversal size | May omit valid deeper rows |
| Visited-node check | Graphs and possibly cyclic data | Requires tracking the path |
Cycle guards for graph traversal
A graph can contain a cycle. For example, node 1 can lead to node 2, node 2 to node 3, and node 3 back to node 1. A recursive query must avoid visiting a node already on its current path.
In PostgreSQL, an array can store visited node IDs:
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 w
JOIN edges e ON e.from_id = w.id
WHERE e.to_id <> ALL (w.path)
)
SELECT id, path
FROM walk;The anchor starts at node 1 and records [1]. Before following an edge, the WHERE clause checks that the destination is not already in path. The array concatenation operator || adds the new node to the path.
A path-based guard prevents a cycle on the current route. It does not necessarily prevent reaching the same node through two different routes. If you need each node only once across the entire traversal, use a separate strategy supported by your database, such as a visited set outside the recursive query or a dialect-specific cycle feature.
Practical checklist
Before running a recursive CTE, verify:
- The anchor returns the intended starting rows.
- The recursive member moves toward a known boundary or reaches fewer children.
- A depth limit protects against unexpectedly large input.
- A cycle guard is present when the data is a graph or may be malformed.
- The selected columns have compatible types in both members.
- You tested empty roots, leaf nodes, cycles, and unusually deep data.
Exercise
In the number-generating CTE, what happens if the recursive member uses WHERE n > 0 instead of WHERE n < 5?
Show answer
Starting from 1, the condition remains true as n increases, so the query has no logical stopping point. It may continue until the database cancels it or reaches a configured recursion limit.