Sub topic 8
Graphs and Cycle Detection
Prerequisites
This chapter assumes you can read a basic recursive CTE, meaning an anchor member, a recursive member joined by UNION ALL, and a termination condition. It also assumes you have tracked depth and path columns through a tree. You should be comfortable with self-joins and with a table that stores one row per edge.
Why graphs break the tree assumption
An org chart is a tree. Every employee has one manager, and following manager_id upward always ends at the top. A recursion that walks down a tree stops on its own, because it eventually runs out of children.
A general graph has no such guarantee. A node can have several incoming edges, and edges can lead back to a node you already visited. Examples are road networks, flight routes, follow relationships, and package dependencies. If a cycle exists, the recursive member keeps finding "new" rows forever. Each pass produces a row with a longer path, so the working table never becomes empty.
Use this graph for the rest of the chapter. Create it with:
CREATE TABLE edges (
src INTEGER NOT NULL,
dst INTEGER NOT NULL
);
INSERT INTO edges (src, dst) VALUES
(1, 2), (2, 3), (3, 1), (2, 4), (4, 5);Start from node 1 with no guard, and the query visits 1, 2, 3, 1, 2, 3, and so on without end. In a database with no recursion limit, the query runs until it exhausts memory or disk. SQL Server stops at 100 levels with an error, and other databases may keep going.
Detecting cycles with a path array
The most reliable defence is to remember the nodes each row has already passed through and refuse to step onto one of them. In PostgreSQL an array holds that memory:
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;Three parts do the work:
- The anchor seeds
pathwith both ends of the first edge, so the start node is already in the visited list. r.path || e.dstappends the newly reached node to the array.e.dst <> ALL (r.path)is true only whene.dstdiffers from every element of the array. An edge that would revisit a node produces no row, so that branch ends.
On the sample graph, the query evaluates like this:
| Iteration | Rows produced | Edge rejected |
|---|---|---|
| Anchor | `2 {1,2}` | none |
| 1 | `3 {1,2,3}`, `4 {1,2,4}` | none |
| 2 | `5 {1,2,4,5}` | edge 3 to 1, because 1 is already in `{1,2,3}` |
| 3 | none | node 5 has no outgoing edges |
The working table is empty after iteration 3, so the recursion stops. The final result has four rows, for nodes 2, 3, 4, and 5. Node 1 never appears as a destination, because it is in every path from the start.
The check applies to each path separately. Two different routes may both pass through node 4, and both rows are kept. What is forbidden is a single route visiting a node twice.
Adding a depth limit as a second guard
A path check proves termination only if the graph is finite, which it always is. It can still be slow, though, because the number of distinct simple paths can grow exponentially. A depth cap bounds the work independent of the graph's shape:
WITH RECURSIVE reach AS (
SELECT src, dst, ARRAY[src, dst] AS path, 1 AS depth
FROM edges
WHERE src = 1
UNION ALL
SELECT r.src, e.dst, r.path || e.dst, r.depth + 1
FROM reach r
JOIN edges e ON e.src = r.dst
WHERE e.dst <> ALL (r.path)
AND r.depth < 10
)
SELECT dst, path, depth FROM reach;A depth limit alone is not cycle detection. Without the path check, this query would stop at depth 10 but would still return nodes 1, 2, and 3 many times over. Use the depth limit to bound cost and the path check to keep results meaningful.
The CYCLE clause in PostgreSQL 14 and later
PostgreSQL 14 added the SQL-standard CYCLE clause, which builds and tests the path for you:
WITH RECURSIVE reach(src, dst) AS (
SELECT src, dst FROM edges WHERE src = 1
UNION ALL
SELECT r.src, e.dst
FROM reach r
JOIN edges e ON e.src = r.dst
)
CYCLE dst SET is_cycle USING path
SELECT src, dst, is_cycle, path
FROM reach
WHERE NOT is_cycle;CYCLE dst names the column to watch. SET is_cycle adds a boolean column that becomes true on a row whose dst already appeared earlier on its own path. USING path names the array column that tracks visited values. The database does not recurse beyond a row marked as a cycle. That row is still returned, which is why the outer query filters with WHERE NOT is_cycle. You can also leave that filter out to see exactly where each cycle closes, which helps when you audit dirty data.
Cycle detection without arrays
SQLite, MySQL, and SQL Server have no array type. The common substitute is a delimited string holding the visited nodes, tested with a substring search. This is the SQLite version:
WITH RECURSIVE reach(dst, path) AS (
SELECT dst, ',' || src || ',' || dst || ','
FROM edges
WHERE src = 1
UNION ALL
SELECT e.dst, r.path || e.dst || ','
FROM reach r
JOIN edges e ON e.src = r.dst
WHERE instr(r.path, ',' || e.dst || ',') = 0
)
SELECT dst, path FROM reach;MySQL needs CONCAT and LOCATE, because || means logical OR there by default. It also needs an explicit cast on the anchor:
WITH RECURSIVE reach (dst, path) AS (
SELECT dst, CAST(CONCAT(',', src, ',', dst, ',') AS CHAR(200))
FROM edges
WHERE src = 1
UNION ALL
SELECT e.dst, CONCAT(r.path, e.dst, ',')
FROM reach r
JOIN edges e ON e.src = r.dst
WHERE LOCATE(CONCAT(',', e.dst, ','), r.path) = 0
)
SELECT dst, path FROM reach;MySQL takes each recursive column's type from the anchor member. Without the CAST, the column would be only as wide as the first path string, and longer paths fail or truncate. SQL Server has the same rule: the anchor and recursive member must produce identical types, so cast the anchor path to something like VARCHAR(200). Use CHARINDEX for the substring test and + for concatenation. Leave out the RECURSIVE keyword.
Undirected graphs
If the edge (a, b) means a connection in both directions, but you store it once, the recursion must follow it either way. Build a symmetric edge list first:
WITH RECURSIVE both_ways(src, dst) AS (
SELECT src, dst FROM edges
UNION ALL
SELECT dst, src FROM edges
),
reach AS (
SELECT src, dst, ARRAY[src, dst] AS path
FROM both_ways
WHERE src = 1
UNION ALL
SELECT r.src, b.dst, r.path || b.dst
FROM reach r
JOIN both_ways b ON b.src = r.dst
WHERE b.dst <> ALL (r.path)
)
SELECT dst, path FROM reach;Here the path check is essential. Every undirected edge is a two-node cycle, so without it the walk would bounce between neighbours immediately. The first CTE is not itself recursive, but PostgreSQL accepts the RECURSIVE keyword once for the whole WITH list.
Path explosion and choosing a strategy
The path check keeps every distinct simple path, not every distinct node. In a graph shaped like a ladder, where each of 20 layers has two nodes fully connected to the next layer, there are 2^20 routes to the last layer, although only 40 nodes. Such a query can be slow or exhaust memory even though it terminates.
If you only need which nodes are reachable, and not the routes, choose one of these:
- Keep only the node column and use
UNIONinstead ofUNION ALL, so a node already in the result is not added again. This works only when every column of the row is identical for repeat visits, so no path or depth column is allowed. The next chapter covers it. - Add a depth column and select the minimum depth per node in the outer query, with a depth cap to keep the walk bounded.
- Move the traversal into application code or a graph database if graphs are large and queries are frequent.
Common errors
- The query runs until it hits a limit: the path check tests the wrong column. It must test the column the next join step uses, here
e.dst. - Cycles are missed because the anchor path omits the start node. The walk may then return to the start once.
- Results are missing in MySQL or SQL Server: the anchor path column is too narrow, or the delimiter is missing.
- Rows are duplicated: several routes reach the same node, and the outer query does not apply
DISTINCTor an aggregate.
Exercise
You add the edge (5, 2) to the sample table. Starting from node 1, what does the path-array query return, and does it still terminate?
Show answer
It still terminates and returns the same four rows (nodes 2, 3, 4, 5). The only new candidate is the step from 5 to 2 on the path {1,2,4,5}. The filter e.dst <> ALL (r.path) rejects it because 2 is already in the path, so iteration 3 produces no rows and the working table is empty.
Exercise
Why can a path built as the string '1,2,11' wrongly block a step to node 1 or allow a wrong match, and how do you fix it?
Show answer
A plain substring search for '1' matches inside '11', so it reports a visit that never happened. The string should wrap every node in delimiters, such as ',1,2,11,', and the test should search for ',' || node || ','. That makes a match possible only on a whole node id.