Sub topic 6
Stopping recursion: conditions, depth limits, and cycle guards
A recursive CTE that never stops is the most common way to hang a query. This chapter covers how the database decides to stop, how to write a termination condition, how to add a depth limit as a safety net, and how to guard against cycles in the data.
This chapter assumes you can write the anchor member and recursive member of a recursive CTE and that you know what UNION ALL does. Examples use PostgreSQL syntax. The dialect table later in the chapter covers other engines.
How a recursive CTE actually ends
A recursive CTE does not run "until a condition is true". It runs in rounds, and it ends when a round produces no rows.
- The anchor member runs once. Its rows go into the result and into a working table.
- The recursive member runs against the working table only, not the whole result so far. Its output is added to the result and replaces the working table.
- If the recursive member returned zero rows, the query ends. Otherwise go back to step 2.
Every technique in this chapter is a way to make the recursive member return zero rows at the right time. The source of the empty round can be one of three things:
- The data runs out. A leaf employee has no reports, so the join finds nothing.
- A condition you wrote filters everything out.
- A guard removes rows that would repeat.
Termination by a condition in the recursive member
The simplest case is a counter. The WHERE clause inside the recursive member is what stops it.
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 5
)
SELECT n FROM numbers;Round 1 produces 2, round 2 produces 3, and so on. When the working table holds 5, the condition n < 5 is false, so the recursive member returns nothing and the query ends. The result is 1 to 5.
The condition must be inside the recursive member
A common mistake is to put the limit in the outer query:
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM numbers
)
SELECT n FROM numbers WHERE n <= 5;This looks right but never finishes in PostgreSQL. The outer WHERE filters rows after they are produced. It does not change what the recursive member returns, so each round still produces a new row. The query keeps running until memory or disk runs out, or until you cancel it.
An outer LIMIT can end the query early on some engines. PostgreSQL and SQLite stop producing rows once the limit is reached. Treat this as a trick for quick tests, not as the termination logic of a query you ship. Other engines may compute the full recursion first.
Natural termination in hierarchies
Walking a tree, as in the organization chart from the previous chapter, needs no explicit condition. Each round finds the direct reports of the previous round's employees. The chain of managers is finite, so eventually the join finds no employees and the recursion ends.
That only holds if the data really is a tree. A manager who reports to themselves, or two employees who manage each other, makes the chain infinite. So even when you expect natural termination, you should decide what protects the query from bad data.
Depth limits
A depth limit is a counter column that you increment each round and test in the recursive member. It caps the number of rounds no matter what the data looks like.
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;Here the check is o.depth < 10. It tests the row being expanded, not the row being created. A row at depth 10 can still appear in the result, because it is produced from a row at depth 9. It just is not expanded further. So the maximum depth in the output is 10, and you get at most 11 levels counting depth 0.
Choose the limit from what the data can legitimately contain. A reporting chain is rarely deeper than 15 levels, so a limit of 50 or 100 does not cut off real data but still catches a loop quickly.
What a depth limit does and does not do
A depth limit guarantees the query ends. It does not make the result correct when the data has cycles. Consider this graph, where nodes 2, 3 and 1 form a loop:
CREATE TABLE edges (from_id int, to_id int);
INSERT INTO edges VALUES (1, 2), (2, 3), (3, 1), (3, 4);Walking from node 1 with only a depth limit:
WITH RECURSIVE walk AS (
SELECT 1 AS id, 0 AS depth
UNION ALL
SELECT e.to_id, w.depth + 1
FROM walk w
JOIN edges e ON e.from_id = w.id
WHERE w.depth < 5
)
SELECT id, depth FROM walk ORDER BY depth;The query returns seven rows, with ids 1, 2, 3, 1, 4, 2, 3 at depths 0 to 5. It stops, but nodes 1, 2 and 3 appear more than once because the walk goes around the loop. With a larger limit you would get more repeats, and in a graph with many branches the row count grows exponentially with the limit. A depth limit protects against an endless loop, but it does not remove the repeated work.
Cycle guards
A cycle guard stops the walk from visiting the same node twice. The usual technique is to carry the list of visited nodes in an array and skip any edge that leads back into it.
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;With the edges table above, this returns four rows:
| id | path |
|---|---|
| 1 | {1} |
| 2 | {1,2} |
| 3 | {1,2,3} |
| 4 | {1,2,3,4} |
At node 3 the edge back to node 1 is rejected because 1 is already in {1,2,3}. The edge to node 4 is allowed. The next round finds nothing and the query ends.
The expression e.to_id <> ALL (w.path) is true only if to_id differs from every element of the array. Note what the path records: the nodes on the route from the start to this row, not every node seen anywhere in the query. If two different routes reach node 4, you get two rows for it, each with its own path. That is correct for "list all paths", but it is not the same as "list all reachable nodes".
The cost of path arrays
Each row carries its own array, so memory and comparison cost grow with depth. For long paths over large graphs this becomes the dominant cost. If you only need reachability, not the paths, the next technique is cheaper.
Deduplication with UNION
Replacing UNION ALL with UNION makes the engine discard any new row that exactly matches a row already in the result. When the row contains only the node id, a repeated node is a duplicate, and the walk ends at the cycle.
WITH RECURSIVE reach(id) AS (
SELECT 1
UNION
SELECT e.to_id
FROM reach r
JOIN edges e ON e.from_id = r.id
)
SELECT id FROM reach;This returns 1, 2, 3 and 4 once each. Node 1 is rediscovered through the edge 3 -> 1, recognized as a duplicate, and dropped, so the working table becomes empty.
This only works when whole rows can be equal. If you add a depth or path column, every row is different from the earlier ones, nothing is discarded, and the guard stops working. Also, UNION is not accepted in a recursive CTE on every engine. SQL Server requires UNION ALL.
The CYCLE clause
PostgreSQL 14 and later can generate the bookkeeping for you with a CYCLE clause, which is part of the SQL standard. Oracle also supports it.
WITH RECURSIVE walk(id) AS (
SELECT 1
UNION ALL
SELECT e.to_id
FROM walk w
JOIN edges e ON e.from_id = w.id
) CYCLE id SET is_cycle USING path
SELECT id, is_cycle, path
FROM walk
WHERE NOT is_cycle;The engine tracks the values of id along each route. When a row repeats an id already on its route, the engine marks it with is_cycle = true and does not expand it further. The marked row is still returned, which is why the final query filters on NOT is_cycle. Keep those marked rows if you want to report which edges close a loop.
Engine limits as a last resort
Some engines apply their own limit on rounds. These are safety nets, not design tools.
| Engine | Default behavior | How to change it |
|---|---|---|
| PostgreSQL | No limit. Runs until memory or disk is exhausted. | Add a depth limit or cycle guard. Use `statement_timeout` as a backstop. |
| MySQL 8 | Fails with an error after 1000 rounds. | Set `cte_max_recursion_depth`. |
| SQL Server | Fails with an error after 100 rounds. | Add `OPTION (MAXRECURSION n)`. A value of 0 means no limit. |
| SQLite | No round limit. | A `LIMIT` on the recursive query stops it. |
| Oracle | No round limit. | Use the `CYCLE` clause for loops. |
Be aware of the difference between failing and truncating. MySQL and SQL Server raise an error when the limit is hit, so a bad query is visible. A depth condition in the WHERE silently returns partial results. If silent truncation would be dangerous, for example when computing totals over a hierarchy, prefer a cycle guard and let the query fail loudly on real corruption.
Choosing a guard
- If the data is guaranteed to be a tree, rely on natural termination. Still add a generous depth limit if bad data would be costly.
- If the data may contain cycles, use a cycle guard. A depth limit alone gives repeated rows.
- If you only need the set of reachable nodes, use
UNIONor aCYCLEclause instead of path arrays. - If you need the paths, use a path array or
CYCLE ... USING path. - If a query is exploratory, set
statement_timeoutor the engine's recursion limit so a mistake costs seconds, not hours.
Other things that go wrong
- Forgetting to change the value.
SELECT n FROM numbers WHERE n < 5withoutn + 1returns the same row every round and never ends. - Type mismatch. The recursive member must return the same column types as the anchor. In PostgreSQL, an anchor of
'a'is a different type thanvarchar(10)in a recursive step, and the query fails with an error. Cast the anchor to the type you need. - Off-by-one limits. Decide whether the limit applies to the row being expanded or the row being produced, and test the edge case with a tiny limit such as 1.
- Joins that multiply rows. An extra join in the recursive member can produce several rows per parent. This grows row counts quickly even without cycles.
Exercise
A recursive CTE over a categories(id, parent_id) table hangs. The query is WITH RECURSIVE tree AS (SELECT id, parent_id, 0 AS depth FROM categories WHERE parent_id IS NULL UNION ALL SELECT c.id, c.parent_id, t.depth + 1 FROM categories c JOIN tree t ON c.parent_id = t.id) SELECT * FROM tree WHERE depth < 20;. Why does the outer WHERE depth < 20 not help, and what are two changes that fix the problem?
Show answer
The outer filter runs after rows are produced and does not change what the recursive member returns, so if the data has a cycle (for example, a category that is its own ancestor), each round still produces rows. First fix: move the limit into the recursive member by adding WHERE t.depth < 20 to the second SELECT. Second fix: add a cycle guard, such as a path array with WHERE c.id <> ALL (t.path), or a CYCLE id SET is_cycle USING path clause in PostgreSQL 14 or later. The cycle guard is better because it also avoids repeated rows.
Exercise
Using the edges table from this chapter, you change the UNION query in the "Deduplication with UNION" section by adding a depth column that increases by 1 each round. The query now runs until you hit the limit of your engine. Why did the change break the guard?
Show answer
UNION removes a new row only if it is identical to a row already in the result. Once depth is part of the row, a revisit of node 1 at depth 3 differs from the first visit at depth 0, so it is not a duplicate and the cycle is never detected. Remove the depth column, or use a path-based cycle guard instead.