How do you implement a recursive query in SQL?

Instruction: Explain the concept of recursion in SQL and provide an example where it's applicable.

Context: This question gauges the candidate's understanding of advanced query techniques, including recursion, to process hierarchies or repetitive patterns.

Updated

Official answer

A recursive CTE combines a starting query with a recursive term that reads the previous iteration. It can traverse hierarchies or graphs. Termination and duplicate/path semantics must be deliberate.

This PostgreSQL graph deliberately contains a cycle:

WITH RECURSIVE edges(parent_id, child_id) AS (
  VALUES (1,2), (2,3), (3,1), (1,4)
), walk(node_id, path) AS (
  SELECT 1, ARRAY[1]
  UNION ALL
  SELECT e.child_id, w.path || e.child_id
  FROM walk w
  JOIN edges e ON e.parent_id = w.node_id
  WHERE NOT e.child_id = ANY(w.path)
)
SELECT node_id, path
FROM walk
ORDER BY path;

The paths are [1], [1,2], [1,2,3] and [1,4]. The path check prevents revisiting a node within that path. With converging routes, a node may still appear through several paths; that is different from returning each reachable node once.

Use a unique root identifier. A depth bound can cap work but may truncate valid results and should be reported. Cycle protection does not prevent a large number of simple paths in a dense graph; bound resources and choose traversal semantics for the actual task. Recursive syntax differs by database.

Related Questions