Learn SQL
-- subqueries.graph_traversal_recursive

Graph Traversal in SQL

Paths, cycles, depth — with guards

--concept

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.

--how it works
1

Anchor starts

Seed rows with path ARRAY[id], depth 1 — frontier initialized.

2

Extend one hop

JOIN edges to frontier — each pass adds a layer.

3

Guard cycles

WHERE NOT (next = ANY(path)) + depth cap — termination guaranteed.

4

Union the layers

UNION ALL accumulates passes; UNION dedups at per-pass sort cost.

--visualization
ANCHOREXTENDGUARD
Stage 1 / 3
Anchor: roots with path [id], depth 1.
--example
query.sql
1-- path-carrying recursion (PostgreSQL arrays):
2-- SELECT ..., path || e.id, depth + 1 ... WHERE NOT (e.id = ANY (path))
Result
useanatomy
org chartanchor + extend + guard
graphsdepth 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.

--variants

Reporting chain walk

Employee → manager layers with depth.

query.sql
1WITH RECURSIVE reports AS (
2 SELECT id, manager_id, name, 1 AS depth FROM employees WHERE manager_id IS NULL
3 UNION ALL
4 SELECT e.id, e.manager_id, e.name, r.depth + 1 FROM employees e JOIN reports r ON e.manager_id = r.id
5) SELECT * FROM reports;
Result
layerdepth
root1
layer-22
1Anchor roots the forest.
2Each pass hangs direct reports one deeper.
3Fixpoint when a pass adds nothing.

Cycle guard (arrays)

Visited-path stops infinite loops.

query.sql
1-- ... path || e.id, depth + 1 ... WHERE NOT (e.id = ANY (path)) AND depth < 10
Result
caseresult
cyclic graphterminates
1Path history travels per row.
2Revisit blocked by ANY check.
3Depth cap backstops hostile data.
--key facts
Three partsanchor + self-extend + termination
Cycle guardvisited-path or depth cap — mandatory
Boundaryshallow SQL; deep graphs elsewhere
--use cases
Org charts, BOM explosions, reachability
Path/depth columns for UI trees
--under the hood
Recursion iterates working-set joins — index the edge (from_id); breadth-first by default layering.
Deep analytics (PageRank, shortest-path over millions) belong in graph engines.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.