← Back to SQL, page 6

sql-0110 · Hard senior

Explain the difference between UNION and UNION ALL inside a recursive CTE, and how to stop a traversal from looping on a graph with cycles.

With UNION ALL every produced row is kept, so a cycle in the data makes the recursion run forever. UNION discards rows already produced, which stops a cycle only when the repeated rows are identical; once you carry a depth or path column, rows differ and UNION no longer helps. The reliable guard is to carry the visited path and refuse to revisit a node, or to cap the depth.

Full answer

Graphs, unlike trees, can loop back. A small route map with a cycle A to B to C to A:

sql
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:

sql
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:

sql
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;
nodepathdepth
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:

sql
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;
nodedepthis_cycle
A0false
B1false
C2false
D2false
A3true
sql
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