Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 73/ 160
04. Subqueries & Common Table Expressions (CTEs)

Graph Traversal & Cycle Detection in Recursive CTEs

Traverse graphs safely and detect cycles with path arrays or visited sets.

AdvancedGraph Walk · Cycle Detection3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Accounts within 2 hops of a flagged accountQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH RECURSIVE2  near AS (3    SELECT4      to_id AS id,5      1 AS hops,6      ARRAY[42, to_id] AS path7    FROM8      transfers9    WHERE10      from_id = 4211    UNION ALL12    SELECT13      t.to_id,14      n.hops + 1,15      n.path || t.to_id16    FROM17      near n18      JOIN transfers t ON t.from_id = n.id19    WHERE20      n.hops < 221      AND NOT t.to_id = ANY (n.path)22  )23SELECT24  id,25  MIN(hops) AS hops26FROM27  near28GROUP BY29  id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/29
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative reachable accounts4 sample rows
Representative reachable accounts
idhops
171
231
882
1052

Note: Illustrative directed transfers from account 42; cycles revisiting an account are excluded by the path guard.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

The same check with the CYCLE clauseQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH RECURSIVE2  walk (job, node) AS (3    SELECT4      job,5      depends_on6    FROM7      edges8    UNION ALL9    SELECT10      w.job,11      e.depends_on12    FROM13      walk w14      JOIN edges e ON e.job = w.node15  ) CYCLE node16SET17  is_cycle USING path18SELECT DISTINCT19  job20FROM21  walk22WHERE23  is_cycle;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/23
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative jobs involved in cycles2 sample rows
Representative jobs involved in cycles
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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

(PostgreSQL 14+).

Key takeaway: Mark revisits as cycles; watch path explosion in dense graphs.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Schema

Model the edges

Store one row per directed link with an index on from_id; add the reverse direction for undirected graphs.

Focus at this step

edges(from_id, to_id), INDEX (from_id)

What to watch at this step
Undirected
both directions
Tip: use ← → to move between steps

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

Recursive CTE with path array
Best for: Dependency checks, small to medium graphs, a few hops

Strengths: Runs where the data already is; precise cycle reporting.

Watch out: Route count explodes in dense graphs.

Recursive CTE with UNION and depth limit
Best for: Reachability within a few hops

Strengths: Deduplicates rows each iteration; bounded work.

Watch out: Loses the individual paths.

Graph database or library
Best for: Large, highly connected graphs and deep traversals

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?
Interview tip: Mention the path array and the depth limit before anything else. Showing you know graphs can loop and explode is the key insight interviewers look for.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Generating Calendars, Date Spines & Number Sequences with Recursive CTEs
Next topic
Data-Modifying CTEs (WITH deleted AS (DELETE ... RETURNING *))