← Back to SQL, page 19

sql-0376 · Hard senior

A recursive query that walks a management chain never finishes on some data. Why, and how do you make it safe?

The data contains a cycle (A manages B, B manages A), so the recursion keeps adding the same people forever. Track the visited path and stop when the next id is already in it, or cap the depth. PostgreSQL 14+ also has a CYCLE clause for this.

Full answer
sql
CREATE TABLE org (id INTEGER PRIMARY KEY, name TEXT, manager_id INTEGER);
INSERT INTO org VALUES (1, 'Ana', 3), (2, 'Ben', 1), (3, 'Cy', 2), (4, 'Dee', 1);

The query as written:

sql
WITH RECURSIVE chain(id, name, depth) AS (
  SELECT id, name, 0 FROM org WHERE id = 2
  UNION ALL
  SELECT o.id, o.name, c.depth + 1 FROM org o JOIN chain c ON o.id = (SELECT manager_id FROM org WHERE id = c.id)
)
SELECT * FROM chain LIMIT 7;
idnamedepth
2Ben0
1Ana1
3Cy2
2Ben3
1Ana4
3Cy5
2Ben6

Ben's manager is Ana, Ana's is Cy and Cy's is Ben again, so the chain repeats. The LIMIT 7 was added here only so the demonstration ends; without it the query runs until memory or a timeout stops it.

A corrected version:

sql
WITH RECURSIVE chain(id, name, depth, path) AS (
  SELECT id, name, 0, '/' || id || '/' FROM org WHERE id = 2
  UNION ALL
  SELECT o.id, o.name, c.depth + 1, c.path || o.id || '/' FROM org o JOIN chain c ON o.id = (SELECT manager_id FROM org WHERE id = c.id)
  WHERE c.path NOT LIKE '%/' || o.id || '/%'
)
SELECT id, name, depth, path FROM chain;
idnamedepthpath
2Ben0/2/
1Ana1/2/1/
3Cy2/2/1/3/

The path string records visited ids, and the WHERE stops before revisiting one, so the walk ends after Ben, Ana and Cy. Using UNION instead of UNION ALL also stops exact duplicate rows, but not here, because depth differs on each lap. Fixing the data (and adding a check on updates) is the real cure; the guard keeps queries safe meanwhile.

sql
CREATE TABLE org (id INTEGER PRIMARY KEY, name TEXT, manager_id INTEGER);
INSERT INTO org VALUES (1, 'Ana', 3), (2, 'Ben', 1), (3, 'Cy', 2), (4, 'Dee', 1);

WITH RECURSIVE chain(id, name, depth) AS (
  SELECT id, name, 0 FROM org WHERE id = 2
  UNION ALL
  SELECT o.id, o.name, c.depth + 1 FROM org o JOIN chain c ON o.id = (SELECT manager_id FROM org WHERE id = c.id)
)
SELECT * FROM chain LIMIT 7;

WITH RECURSIVE chain(id, name, depth, path) AS (
  SELECT id, name, 0, '/' || id || '/' FROM org WHERE id = 2
  UNION ALL
  SELECT o.id, o.name, c.depth + 1, c.path || o.id || '/' FROM org o JOIN chain c ON o.id = (SELECT manager_id FROM org WHERE id = c.id)
  WHERE c.path NOT LIKE '%/' || o.id || '/%'
)
SELECT id, name, depth, path FROM chain;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Cycles make recursive CTEs run forever
  • Track the visited path
  • Cap depth as a backstop
  • UNION only removes identical rows
  • PostgreSQL has a CYCLE clause

Common mistakes

  • Assuming hierarchical data never has cycles
  • Relying on UNION when a depth column differs

Follow-ups

  • How would you find all cycles in the table?
  • How would you stop updates from creating a cycle?

Tips

  • Show the path guard