Transitive closure with a recursive CTE
Seed, expand, and let UNION's deduplication be the termination proof.
The task
From an edges(src, dst) table you want everything reachable from node 1, whether that takes one hop or ten.
The snippet
Written for PostgreSQL. Versions for SQL Server and Oracle are under Variations.
WITH RECURSIVE reachable AS (
SELECT src, dst FROM edges WHERE src = 1
UNION
SELECT r.src, e.dst
FROM reachable r
JOIN edges e ON e.src = r.dst
)
SELECT DISTINCT dst
FROM reachable
WHERE dst <> 1
ORDER BY dst;
它的運作方式
The anchor selects the direct neighbours; the recursive step joins every frontier node to its own outgoing edges until no new rows appear. Using UNION rather than UNION ALL discards rows already produced, which both dedupes the closure and guarantees termination even if the graph has cycles. The statement runs as-is on PostgreSQL, MySQL 8 and SQLite. SQL Server and Oracle reject the RECURSIVE keyword and allow only UNION ALL in a recursive CTE, so there you need a depth cap (variant below) or Oracle's CYCLE clause to survive cycles.
Variations
Keep the hop count
WITH RECURSIVE reachable AS (
SELECT src, dst, 1 AS hops FROM edges WHERE src = 1
UNION
SELECT r.src, e.dst, r.hops + 1
FROM reachable r
JOIN edges e ON e.src = r.dst
WHERE r.hops < 20
)
SELECT dst, MIN(hops) AS shortest_hops
FROM reachable
WHERE dst <> 1
GROUP BY dst
ORDER BY dst;
SQL Server and Oracle: UNION ALL with a depth cap
SQL Server OracleWITH reachable (dst, depth) AS (
SELECT dst, 1 FROM edges WHERE src = 1
UNION ALL
SELECT e.dst, r.depth + 1
FROM reachable r
JOIN edges e ON e.src = r.dst
WHERE r.depth < 20
)
SELECT DISTINCT dst
FROM reachable
WHERE dst <> 1
ORDER BY dst;
Questions that come up
Why does UNION terminate on cyclic graphs?
Because a row is only fed back into the recursive step if it differs from every row already produced. Once every (src, dst) pair has been emitted, the recursion has nothing new and stops, unlike UNION ALL which would loop forever on a cycle. The hop-count variant breaks this: hops makes every lap of a cycle a new row, which is why it carries the WHERE r.hops < 20 cap.
Keep reading
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.