Sub topic 5
Making sure the recursion stops
A recursive query that never stops is the most common failure when you first write WITH RECURSIVE. This chapter assumes you know the anatomy of a recursive CTE (anchor member, recursive member, UNION ALL) and the working-table model from earlier chapters. It also assumes you can read SELECT, WHERE, JOIN, and basic aggregates.
By the end you will be able to explain why a recursion terminates, name the three common ways it fails to, and apply a guard: a condition in the recursive member, a depth limit, a path check, or a dialect setting.
The termination rule
A recursive CTE stops when an iteration produces zero new rows. The database runs the recursive member against the working table, which holds only the rows from the previous iteration. If that run returns nothing, the loop ends and the accumulated rows become the CTE result.
So termination is a property of your data and your WHERE clause together. The database does not check for you that the loop will end. It simply keeps going while rows appear.
WITH RECURSIVE n(i) AS (
SELECT 1
UNION ALL
SELECT i + 1 FROM n WHERE i < 10
)
SELECT i FROM n;Here the anchor produces 1. Each iteration produces i + 1 only if the current i is below 10. When i is 10, the WHERE clause rejects the row, the iteration returns nothing, and the recursion ends. The output is the numbers 1 through 10.
Three ways recursion fails to stop
1. A missing or wrong stop condition
The simplest bug is leaving out the WHERE clause in a series generator:
WITH RECURSIVE n(i) AS (
SELECT 1
UNION ALL
SELECT i + 1 FROM n
)
SELECT i FROM n;Every iteration produces one new row, so the loop never reaches an empty iteration. Whether this "runs forever" depends on the dialect. Some engines stream rows to the client and keep going until memory or disk runs out. Others hit a built-in limit and raise an error.
A related mistake is a condition that can never become false, for example WHERE i <> 10 when the series starts at 11, or a comparison on the wrong column.
2. Cycles in the data
Hierarchies stored as trees cannot loop, but the data may not be a clean tree. Suppose employees contains a row where employee 5 reports to employee 9, and employee 9 reports to employee 5. Walking down from 5 reaches 9, then 5, then 9, and so on. Each iteration finds a "new" row that is really a repeat.
Graphs have the same problem. Any edge table with a path back to an earlier node contains a cycle. Cycle handling gets its own treatment in a later chapter, but the basic path-check guard appears below because it is one of the standard ways to stop.
3. Exponential growth
A recursion can terminate and still be unusable. If every row has many children, or a graph has many routes to the same node, each iteration multiplies the row count. The query ends eventually but only after producing far more rows than the data justifies. Treat unexpectedly large row counts as a termination problem, because in practice you have to kill the query.
Guard 1: a stop condition on the value
When the recursion generates values, put the limit in the recursive member's WHERE clause, as in the series above. The condition should test the column that changes on each iteration, and the change must move toward the limit. Adding 1 while testing i < 10 works. Subtracting 1 while testing i < 10 does not.
Guard 2: a depth limit
For hierarchies and graphs, carry a depth counter and stop at a maximum. The counter does not fix a cycle. It caps the damage by bounding the number of iterations.
WITH RECURSIVE chain 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, c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
WHERE c.depth < 20
)
SELECT id, name, depth
FROM chain
ORDER BY depth, name;The added WHERE c.depth < 20 ends the recursion after 20 levels even if the data contains a loop. Choose the limit from what the data can plausibly contain. An org chart rarely exceeds 15 levels, so 20 or 50 is a sensible ceiling.
A depth limit has a cost. In a cyclic graph, the query still returns duplicate rows up to the limit, and a legitimate path deeper than the limit is silently cut off. Use it as a safety net and not as a replacement for correct data.
Guard 3: a path check
A path check records the nodes visited so far and refuses to revisit one. This stops cycles exactly where they occur and does not truncate legitimate deep paths. This example uses PostgreSQL array syntax:
WITH RECURSIVE reach AS (
SELECT src, dst, ARRAY[src, dst] AS path
FROM edges
WHERE src = 1
UNION ALL
SELECT r.src, e.dst, r.path || e.dst
FROM reach r
JOIN edges e ON e.src = r.dst
WHERE e.dst <> ALL (r.path)
)
SELECT dst, path FROM reach;The path column starts with the first edge's endpoints. Each step appends the new destination. The filter e.dst <> ALL (r.path) keeps an edge only if its destination is not already in the path. A cycle back to an earlier node fails the filter, so that branch produces no rows and ends.
In engines without arrays, build the path as a delimited string and test it with LIKE or INSTR. Delimit both ends, for example ',1,2,', so that searching for ,1, does not match inside ,11,.
Guard 4: dialect settings
Some engines add a global safety limit on top of your query.
| Dialect | Default behavior | How to change it |
|---|---|---|
| SQL Server | Stops with an error after 100 recursion levels | `OPTION (MAXRECURSION n)`; `0` means no limit |
| MySQL | Stops with an error after `cte_max_recursion_depth` iterations (default 1000) | `SET SESSION cte_max_recursion_depth = n` |
| PostgreSQL | No iteration limit | Use your own condition, or `statement_timeout` |
| SQLite | No iteration limit | Use your own condition, or add `LIMIT` to the CTE |
SQL Server omits the RECURSIVE keyword. Its default of 100 levels surprises people who generate a long series:
WITH n AS (
SELECT 1 AS i
UNION ALL
SELECT i + 1 FROM n WHERE i < 1000
)
SELECT i FROM n
OPTION (MAXRECURSION 1000);Without the hint, this query fails at level 100 even though its own WHERE clause is correct. When the limit is exceeded, SQL Server raises an error and returns no result, so you notice the problem. Setting MAXRECURSION 0 removes that protection, so use it only when your own condition is certain to end the loop.
Guard 5: LIMIT as an emergency stop
In PostgreSQL and SQLite, a LIMIT on the outer query can stop a runaway recursion early, because the engine produces rows lazily and stops once it has enough. For example, SELECT i FROM n LIMIT 10 on the unbounded series above returns 10 rows and ends.
Do not rely on this. It depends on the planner reading the CTE lazily, and it does not work if the query needs all rows first, such as with ORDER BY or GROUP BY on the CTE output. It is useful for testing a new query safely: add LIMIT 100 while you develop, then remove it once you trust the stop condition.
A checklist for each recursive query
- Identify the column that changes on every iteration.
- Confirm the
WHEREclause tests that column, and that the change moves toward making the test false. - Ask whether the data can contain a cycle. If so, add a path check.
- Add a depth limit as a backstop if the cost of a runaway query is high.
- Test with a small anchor first, and with
LIMITwhere your dialect supports lazy evaluation.
Common errors
- Testing the wrong table. Writing
WHERE e.depth < 20when the counter lives on the CTE aliasc. The column must come from the working table. - Off-by-one limits.
WHERE i < 10produces rows up to 10, because the row withi = 9still generates10. The test applies to the input row, not the output row. - Forgetting that the anchor is not filtered. The recursive member's
WHEREclause runs only on later iterations. The anchor always returns its rows. - Assuming
UNIONalways saves you. UsingUNIONinstead ofUNION ALLremoves duplicate rows, which can end some cycles. It fails when each row carries a changing column such asdepthorpath, because then no two rows are identical. A later chapter covers this.
Exercise
This SQL Server query is meant to return the numbers 1 to 500, but it fails with an error about the maximum recursion level. What is wrong, and how do you fix it? WITH n AS (SELECT 1 AS i UNION ALL SELECT i + 1 FROM n WHERE i < 500) SELECT i FROM n;
Show answer
The stop condition is correct, so the query is logically fine. SQL Server limits recursion to 100 levels by default, and this query needs 499 iterations. Add OPTION (MAXRECURSION 500) after the final SELECT (or a larger value). The same query in MySQL would also stop only if it exceeded cte_max_recursion_depth (default 1000), so it would run there as written.
Exercise
An employees table has a data error: employee 7 has manager 12, and employee 12 has manager 7. A recursive org-chart query starting from the top manager reaches employee 7. Explain why a depth limit alone is not a good fix, and name a better guard.
Show answer
Employees 7 and 12 would keep alternating until the depth limit is reached, so the result contains repeated rows for them, and a limit set too low could cut off legitimate deep branches elsewhere. A path check is better: carry the list of visited ids and add the filter that the next employee is not already in the path. The loop then ends at the first repeat with no duplicates and no truncation.