Stop infinite loops in recursive CTEs
The visited list is the guard: no path may pass through the same node twice.
The task
Your edges table can contain cycles and you still want a traversal that terminates without a hard depth limit.
The snippet
Written for PostgreSQL. Versions for MySQL and SQLite are under Variations.
WITH RECURSIVE walk AS (
SELECT e.src, e.dst,
ARRAY[e.src, e.dst] AS visited
FROM edges e
WHERE e.src = 1
UNION ALL
SELECT w.src, e.dst, w.visited || e.dst
FROM walk w
JOIN edges e ON e.src = w.dst
WHERE NOT e.dst = ANY(w.visited)
)
SELECT DISTINCT dst
FROM walk
ORDER BY dst;
Como funciona
Every row carries the path of nodes already visited as an array. The WHERE clause only expands an edge when its destination is not on that path, so no path can loop and the recursion runs dry instead of spinning. The guard is per path, not global: a node reachable by many routes is visited once per route, which can explode on dense graphs. PostgreSQL 14+ builds the same guard in with CYCLE dst SET is_cycle USING path. The depth-cap variant works everywhere once SQL Server and Oracle get their spelling: drop RECURSIVE and name the columns, WITH walk (src, dst, depth) AS (...).
Variations
Depth cap (PostgreSQL, MySQL, SQLite)
PostgreSQL MySQL SQLiteWITH RECURSIVE walk AS (
SELECT e.src, e.dst, 1 AS depth
FROM edges e
WHERE e.src = 1
UNION ALL
SELECT w.src, e.dst, w.depth + 1
FROM walk w
JOIN edges e ON e.src = w.dst
WHERE w.depth < 20
)
SELECT DISTINCT dst FROM walk;
Questions that come up
Visited array or depth cap?
The visited array is exact: it stops precisely at cycles and explores everything else, but it needs arrays (PostgreSQL) or a delimited path string elsewhere. The depth cap works on every engine and is trivial to reason about, but it can silently truncate deep legitimate paths, and on a cyclic graph it still re-walks the loop until the cap, so set the limit to the deepest real path you expect.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.