Graph Traversal in SQL
Paths, cycles, depth — with guards
Recursive CTEs carry path arrays + depth: anchor at start nodes, extend along edges, stop on visited (cycle guard) or depth cap. PG arrays track visitation elegantly (WHERE NOT (e.id = ANY(path))); strings concatenate portable paths. SQL handles shallow hierarchies well; deep graph analytics belongs in graph engines — know the boundary.
Anchor starts
Seed rows with path ARRAY[id], depth 1 — frontier initialized.
Extend one hop
JOIN edges to frontier — each pass adds a layer.
Guard cycles
WHERE NOT (next = ANY(path)) + depth cap — termination guaranteed.
Union the layers
UNION ALL accumulates passes; UNION dedups at per-pass sort cost.
1-- path-carrying recursion (PostgreSQL arrays):2-- SELECT ..., path || e.id, depth + 1 ... WHERE NOT (e.id = ANY (path))
| use | anatomy |
|---|---|
| org chart | anchor + extend + guard |
| graphs | depth cap mandatory |
Each pass extends the frontier one hop with its path history. Cyclic data without the ANY-guard recurses forever — depth caps are the portable backstop.
Reporting chain walk
Employee → manager layers with depth.
1WITH RECURSIVE reports AS (2 SELECT id, manager_id, name, 1 AS depth FROM employees WHERE manager_id IS NULL3 UNION ALL4 SELECT e.id, e.manager_id, e.name, r.depth + 1 FROM employees e JOIN reports r ON e.manager_id = r.id5) SELECT * FROM reports;
| layer | depth |
|---|---|
| root | 1 |
| layer-2 | 2 |
Cycle guard (arrays)
Visited-path stops infinite loops.
1-- ... path || e.id, depth + 1 ... WHERE NOT (e.id = ANY (path)) AND depth < 10
| case | result |
|---|---|
| cyclic graph | terminates |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.