Full answer
Graphs, unlike trees, can loop back. A small route map with a cycle A to B to C to A:
CREATE TABLE routes (src TEXT, dst TEXT);
INSERT INTO routes VALUES ('A','B'),('B','C'),('C','A'),('B','D');With UNION, only the node is carried, so revisiting A produces a row that already exists, and UNION drops it. The recursion ends:
WITH RECURSIVE reach(node) AS (
SELECT 'A'
UNION
SELECT r.dst FROM routes r JOIN reach ON r.src = reach.node
)
SELECT node FROM reach ORDER BY node;| node |
|---|
| A |
| B |
| C |
| D |
As soon as a depth column is added, the row (A, 3) differs from (A, 0) and UNION no longer prevents the loop. A path column with a visited check is the guard that keeps working:
WITH RECURSIVE walk(node, path, depth) AS (
SELECT 'A', '/A/', 0
UNION ALL
SELECT r.dst, w.path || r.dst || '/', w.depth + 1
FROM routes r JOIN walk w ON r.src = w.node
WHERE instr(w.path, '/' || r.dst || '/') = 0
)
SELECT node, path, depth FROM walk ORDER BY depth, node;| node | path | depth |
|---|---|---|
| A | /A/ | 0 |
| B | /A/B/ | 1 |
| C | /A/B/C/ | 2 |
| D | /A/B/D/ | 2 |
The instr check (position or strpos in PostgreSQL) refuses to step into a node already on the path. Delimiters around each name avoid false matches such as 'A' inside 'AB'.
PostgreSQL 14 added a built-in CYCLE clause that does this bookkeeping for you:
WITH RECURSIVE walk(node, depth) AS (
SELECT 'A'::text, 0
UNION ALL
SELECT r.dst, w.depth + 1 FROM routes r JOIN walk w ON r.src = w.node
) CYCLE node SET is_cycle USING path
SELECT node, depth, is_cycle FROM walk ORDER BY depth, node;| node | depth | is_cycle |
|---|---|---|
| A | 0 | false |
| B | 1 | false |
| C | 2 | false |
| D | 2 | false |
| A | 3 | true |
CREATE TABLE routes (src TEXT, dst TEXT);
INSERT INTO routes VALUES ('A','B'),('B','C'),('C','A'),('B','D');
WITH RECURSIVE reach(node) AS (
SELECT 'A'
UNION
SELECT r.dst FROM routes r JOIN reach ON r.src = reach.node
)
SELECT node FROM reach ORDER BY node;
WITH RECURSIVE walk(node, path, depth) AS (
SELECT 'A', '/A/', 0
UNION ALL
SELECT r.dst, w.path || r.dst || '/', w.depth + 1
FROM routes r JOIN walk w ON r.src = w.node
WHERE instr(w.path, '/' || r.dst || '/') = 0
)
SELECT node, path, depth FROM walk ORDER BY depth, node;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- UNION ALL keeps every row; a cycle means infinite recursion
- UNION stops repeats only when whole rows are identical
- Carry a visited path and skip nodes already on it
- PostgreSQL 14+ has a CYCLE clause
Common mistakes
- Relying on UNION after adding a depth column
- Path checks without delimiters that confuse 'A' and 'AB'
Follow-ups
- How would you find the shortest number of hops from A to C?
- What does the SEARCH clause in PostgreSQL do?
Tips
- Mention that a depth cap is a second safety net