Sub topic 5
Making Sure Recursive SQL Queries Stop
Assume you know SELECT, WHERE, ORDER BY, joins, grouping, and subqueries. You should also understand that a recursive common table expression (CTE) has an anchor member, which creates the first rows, and a recursive member, which creates later rows from earlier results.
A recursive query stops when the recursive member produces no more rows, or when a condition prevents another iteration. Without a reliable stopping rule, the query may run until the database reaches a safety limit or returns an error.
Use a boundary condition
A sequence query usually stops with a WHERE condition:
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1
FROM numbers
WHERE n < 10
)
SELECT n
FROM numbers
ORDER BY n;The anchor produces 1. Each recursive iteration adds 1. When the current value is 10, the condition n < 10 is false, so no row enters the next iteration. The result contains the integers from 1 through 10.
The condition must move the query toward an endpoint. A condition such as WHERE n >= 1 does not stop this query because it remains true forever.
Add a depth limit
A depth limit is useful when the data should be a tree but might be damaged. It provides a second guard even when the query follows valid parent-child links.
WITH RECURSIVE hierarchy 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, h.depth + 1
FROM employees AS e
JOIN hierarchy AS h
ON e.manager_id = h.id
WHERE h.depth < 20
)
SELECT id, name, depth
FROM hierarchy
ORDER BY depth, name;This query returns the root employees at depth 0 and allows descendants through depth 20. The limit prevents an unexpectedly deep tree from consuming unlimited resources. It does not detect a cycle by itself. A cycle can still produce rows until the depth limit is reached.
Detect cycles with a path
Graphs can revisit nodes. For example, employee A might report to B while B reports to A. To prevent revisiting a node, carry the nodes already visited and reject the next node if it is already in the path.
PostgreSQL arrays make this pattern direct:
WITH RECURSIVE reach(node_id, path) AS (
SELECT 1, ARRAY[1]
UNION ALL
SELECT e.dst, r.path || e.dst
FROM edges AS e
JOIN reach AS r
ON e.src = r.node_id
WHERE e.dst <> ALL (r.path)
)
SELECT node_id, path
FROM reach;The anchor starts at node 1. The recursive member appends each destination to the path. The WHERE condition refuses a destination already present in that path, so the recursion cannot follow the same route forever.
A path check is different from a depth limit. The path check prevents repeated nodes. The depth limit bounds work even when the graph has a very long acyclic route. Using both is often safest.
Check the dialect's safety setting
Database systems also provide engine-specific limits. PostgreSQL commonly uses a statement timeout rather than a fixed recursive-depth setting. MySQL has cte_max_recursion_depth. SQLite has a recursion limit controlled by the host interface. SQL Server defaults to 100 recursive levels and supports a query hint:
WITH numbers AS (
SELECT 1 AS n
UNION ALL
SELECT n + 1
FROM numbers
WHERE n < 1000
)
SELECT n
FROM numbers
OPTION (MAXRECURSION 1000);These settings are emergency protection, not a replacement for a logical termination condition.
Exercise
Why does a depth limit alone fail to identify a cycle, and what additional technique can prevent repeated nodes?
Show answer
A depth limit only stops after a fixed number of levels. Carry a path of visited node identifiers and reject a recursive step when its next node already appears in that path.