Sub topic 3
Graphs and cycle detection
This chapter assumes you can write a recursive CTE with an anchor and a recursive member, use joins, and aggregate with GROUP BY. A graph can contain cycles, where an edge leads back to a node already visited. A recursive query over a cycle keeps producing rows unless you stop it.
Graphs and cycle detection
The path check below keeps an array of visited nodes and rejects any edge that points to one of them. This is PostgreSQL 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;Rolling up a bill of materials
A bill of materials lists which components each assembly uses. Multiply the quantity at each level, then sum by component in the outer query. A part used in two sub-assemblies then appears once with its total quantity.
UNION versus UNION ALL inside recursion
UNION discards duplicate rows at each iteration. A cycle that returns to an identical row therefore adds nothing, and the recursion ends. UNION ALL keeps duplicates and runs faster, but it needs an explicit guard. Once you carry a path or depth column, each row is unique, so UNION no longer stops the cycle. Use a path check or depth limit instead.
Syntax and limits across dialects
| Database | Keyword | Default recursion limit | Change the limit |
|---|---|---|---|
| PostgreSQL | WITH RECURSIVE | None built in | Add a depth column |
| MySQL 8 | WITH RECURSIVE | 1000 | SET cte_max_recursion_depth |
| SQLite | WITH RECURSIVE | None built in | Add a depth column |
| SQL Server | WITH (no RECURSIVE) | 100 | OPTION (MAXRECURSION n) |
What the recursive member may not do
- It may not use aggregate functions, window functions, or GROUP BY.
- It may reference the CTE only once, in the FROM clause, and not inside a subquery.
- It may not place the recursive reference on the nullable side of an outer join.
Performance and indexing for recursive queries
Each iteration joins the working table to the source table, so index the join column, such as edges(src) or bom(assembly_id). Keep the anchor selective. Path arrays grow with each level, so limit the depth on large data.
When not to use a recursive CTE
Use a closure table when applications query ancestors or descendants often. Use a materialized path when they mostly read whole subtrees. Oracle users can use CONNECT BY for hierarchies. A recursive CTE suits occasional traversals, not heavy write workloads on deep graphs.
Exercise
Why does a plain UNION ALL recursion on a cyclic graph run without end, and what stops it in the path-check query?
Show answer
UNION ALL keeps every row, so a cycle keeps generating new rows indefinitely. The WHERE e.dst <> ALL (r.path) condition rejects any edge that points to a node already in the path, so the recursion cannot revisit a node.