Graph Traversal & Cycle Detection in Recursive CTEs
Traverse graphs safely and detect cycles with path arrays or visited sets.
In plain words
Follow the links from one point, write down where you've been, and stop if you come back to the same place.
Think of it like…
Exploring a city's one-way streets with a notebook: you write down every junction you pass, and if you arrive at one already in your notebook, you've driven in a circle.
Where you’ve seen it
A data platform stores job dependencies as edges(job, depends_on). Before deploying, a check walks the graph from every job: WITH RECURSIVE walk AS (SELECT job AS start, depends_on AS node, ARRAY[job, depends_on] AS path, false AS is_cycle FROM edges UNION ALL SELECT w.start, e.depends_on, w.path || e.depends_on, e.depends_on = ANY(w.path) FROM walk w JOIN edges e ON e.job = w.node WHERE NOT w.is_cycle) SELECT DISTINCT start, path FROM walk WHERE is_cycle; Any row returned is a circular dependency and blocks the deploy.
Words you’ll hear
- Edges table
- One row per directed link: from_id → to_id.
- Reachability
- All nodes that can be reached from a starting node by following edges.
- Path array
- The nodes visited so far on one route, used to detect revisits.
- CYCLE clause
- PostgreSQL 14+ syntax that adds cycle detection to a recursive CTE automatically.
Visual diagram
Theory & example queries
Reachability and shortest hops
The anchor selects edges leaving the start node; the recursive step follows edges from the nodes just reached, appends each new node to a path array and skips any node already in it: WHERE NOT e.to_id = ANY(w.path). The result contains one row per distinct route, so SELECT DISTINCT node gives everything reachable. For undirected relationships such as friendships, either store both directions or recurse over SELECT a, b FROM friends UNION ALL SELECT b, a FROM friends.
PostgreSQL evaluates recursion level by level (breadth first), and you can carry a depth column, so the shortest distance to each node is MIN(depth) GROUP BY node. Adding WHERE depth < 3 to the recursive step limits a search to people within two or three hops, which also keeps the work bounded. PostgreSQL 14's SEARCH BREADTH FIRST BY to_id SET ordercol clause makes the ordering explicit.
WITH RECURSIVE near AS ( SELECT to_id AS id, 1 AS hops, ARRAY[42, to_id] AS path FROM transfers WHERE from_id = 42 UNION ALL SELECT t.to_id, n.hops + 1, n.path || t.to_id FROM near n JOIN transfers t ON t.from_id = n.id WHERE n.hops < 2 AND NOT t.to_id = ANY (n.path) )SELECT id, MIN(hops) AS hopsFROM nearGROUP BY id;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative reachable accounts4 sample rows
| id | hops |
|---|---|
| 17 | 1 |
| 23 | 1 |
| 88 | 2 |
| 105 | 2 |
Note: Illustrative directed transfers from account 42; cycles revisiting an account are excluded by the path guard.
Key takeaway: Follow edges, carry a path, skip revisits; MIN(depth) is the shortest hop count.
Detecting cycles, and the limits of SQL
To report cycles rather than just avoid them, let the step that revisits a node through, mark it, and stop extending marked rows: compute e.to_id = ANY(w.path) AS is_cycle and add WHERE NOT w.is_cycle. PostgreSQL 14+ does this for you with CYCLE to_id SET is_cycle USING path after the CTE body. In MySQL, carry the path as a comma-separated string and test with FIND_IN_SET.
Path tracking keeps every distinct route, and in a dense graph the number of routes grows exponentially even when the number of nodes is small. If you only need reachability, a depth limit plus UNION (which removes duplicate rows each iteration) controls the growth, but very large or highly connected graphs with many-hop questions are where a graph database or a graph-processing library is the better tool.
WITH RECURSIVE walk (job, node) AS ( SELECT job, depends_on FROM edges UNION ALL SELECT w.job, e.depends_on FROM walk w JOIN edges e ON e.job = w.node ) CYCLE nodeSET is_cycle USING pathSELECT DISTINCT jobFROM walkWHERE is_cycle;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative jobs involved in cycles2 sample rows
| job |
|---|
| billing-rollup |
| inventory-sync |
Note: Assumes these job dependency chains contain a repeated node. The CYCLE clause and its exact syntax are PostgreSQL-specific.
(PostgreSQL 14+).
Key takeaway: Mark revisits as cycles; watch path explosion in dense graphs.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Model the edges
Store one row per directed link with an index on from_id; add the reverse direction for undirected graphs.
edges(from_id, to_id), INDEX (from_id)
When to use it & trade-offs
What it is
A graph is stored as an edges table, edges(from_id, to_id), where unlike a tree a node can have many parents and paths can loop back. Recursive CTEs walk graphs to answer reachability (everything X depends on), shortest path in hops and cycle detection (is there a circular dependency?). Because loops are normal in graphs, every traversal must track the nodes already on its path and refuse to revisit them.
Why it matters: Task schedulers, package managers, microservice call maps, social networks and fraud rings are all graphs that live in relational databases. Detecting a circular dependency before it deadlocks a pipeline, or finding everyone within two hops of a flagged account, are real queries teams write. Interviewers use them to test whether you understand recursion beyond simple trees.
When to reach for it
- Circular dependency checks for jobs, packages or migrations
- Finding accounts or people within N hops
- Service dependency and impact analysis
When to avoid or be careful
- Graph recursion without a revisit guard or depth limit
- Full path tracking on dense social graphs
- Treating many-parent graphs as trees
Graph questions in SQL vs a graph database
Strengths: Runs where the data already is; precise cycle reporting.
Watch out: Route count explodes in dense graphs.
Strengths: Deduplicates rows each iteration; bounded work.
Watch out: Loses the individual paths.
Strengths: Built for traversal; graph algorithms included.
Watch out: Another system to load and keep in sync.
Interview signals & numbers to know
When this topic comes up
- “Detect circular dependencies”
- “Everyone within two connections”
- “Which services break if this one fails?”
- Fraud rings
- Recursive CTE on a graph
Benchmarks & rules of thumb
- PostgreSQL 14
- CYCLE and SEARCH clauses
- 1 row
- per distinct route, not per node
- 2–3 hops
- a typical safe search limit on social graphs
Common mistakes & follow-ups
Common interview mistakes
- Recursing over a graph with no path check, so the first cycle makes the query run until it hits a limit or runs out of memory.
- Storing friendships in one direction and finding only half of each person's network.
- Counting reachable nodes with COUNT(*) instead of COUNT(DISTINCT node), counting routes instead.
Likely interviewer follow-ups
- How would you detect a circular dependency between jobs in SQL?
- How do you find the shortest number of hops between two accounts?
- When would you move graph queries to a graph database?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Graph Traversal & Cycle Detection in Recursive CTEs with hands-on SQL practice and interview Q&A.