← Back to SQL, page 15

sql-0286 · Hard senior

Write a recursive query that finds the fewest hops between two stations in a network of direct connections.

Run a breadth-first search with a recursive CTE: start at the source with 0 hops, follow edges while recording the path to avoid revisiting nodes, and stop at a depth limit. Then take the minimum hops among rows that reached the target. SQL can do this for small graphs; large graphs belong in a graph tool or application code.

Full answer
sql
WITH RECURSIVE edges(a, b) AS (VALUES ('A','B'),('A','C'),('B','D'),('C','E'),('E','D'),('D','F')),
 walk(node, hops, path) AS (
  SELECT 'A', 0, '/A/'
  UNION ALL
  SELECT e.b, w.hops + 1, w.path || e.b || '/'
  FROM walk w JOIN edges e ON e.a = w.node
  WHERE instr(w.path, '/' || e.b || '/') = 0 AND w.hops < 5
)
SELECT MIN(hops) AS fewest_hops, (SELECT path FROM walk WHERE node = 'D' ORDER BY hops LIMIT 1) AS path
FROM walk WHERE node = 'D';
fewest_hopspath
2/A/B/D/

The path string prevents loops: a station already on the path is not added again. The depth limit stops the search from exploring long detours. A to D can be reached as A, B, D (2 hops) or A, C, E, D (3 hops); the outer query keeps the shortest.

The number of paths grows quickly with graph size, because every distinct route is a row. For networks beyond a few thousand edges, use a dedicated graph algorithm, PostgreSQL's pgRouting extension, or code that tracks visited nodes globally.

sql
WITH RECURSIVE edges(a, b) AS (VALUES ('A','B'),('A','C'),('B','D'),('C','E'),('E','D'),('D','F')),
 walk(node, hops, path) AS (
  SELECT 'A', 0, '/A/'
  UNION ALL
  SELECT e.b, w.hops + 1, w.path || e.b || '/'
  FROM walk w JOIN edges e ON e.a = w.node
  WHERE instr(w.path, '/' || e.b || '/') = 0 AND w.hops < 5
)
SELECT MIN(hops) AS fewest_hops, (SELECT path FROM walk WHERE node = 'D' ORDER BY hops LIMIT 1) AS path
FROM walk WHERE node = 'D';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Recursive CTEs can run breadth-first searches
  • Track the path to avoid cycles
  • Limit depth to bound the work
  • Paths explode on large graphs

Common mistakes

  • Recursing without cycle protection
  • Using SQL for large-scale routing

Follow-ups

  • How would you return the actual path?
  • Why does UNION not prevent this explosion?

Tips

  • Mention the scaling limit