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;| id | name | depth |
|---|---|---|
| 2 | Ben | 0 |
| 1 | Ana | 1 |
| 3 | Cy | 2 |
| 2 | Ben | 3 |
| 1 | Ana | 4 |
| 3 | Cy | 5 |
| 2 | Ben | 6 |
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;| id | name | depth | path |
|---|---|---|---|
| 2 | Ben | 0 | /2/ |
| 1 | Ana | 1 | /2/1/ |
| 3 | Cy | 2 | /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