LQ
SQL Reference
Practice →
SQL ReferenceExpertRecursive CTEs

Recursive CTEs

Traverse hierarchical data like org charts and trees.

Questions this answers
  • How do I query a hierarchy (org chart, category tree)?
  • How do I find all ancestors or descendants of a node?
  • How do I generate a sequence of numbers?

How it works

Recursive CTEs reference themselves. They have a base case (the starting rows) and a recursive case (how to find the next level). They're the standard way to traverse trees and graphs in SQL — org charts, comment threads, bill-of-materials, category hierarchies.

Walk an org chart

WITH RECURSIVE org AS (
  -- Base: start with the CEO
  SELECT id, name, manager_id, 0 AS level
  FROM employees
  WHERE manager_id IS NULL

  UNION ALL

  -- Recursive: find direct reports
  SELECT e.id, e.name, e.manager_id, org.level + 1
  FROM employees e
  JOIN org ON e.manager_id = org.id
)
SELECT level, name FROM org ORDER BY level;
💡 The UNION ALL joins the base result with each recursive step.

Generate a number series

WITH RECURSIVE nums AS (
  SELECT 1 AS n
  UNION ALL
  SELECT n + 1 FROM nums WHERE n < 100
)
SELECT n FROM nums;

Ready to practise Recursive CTEs?

Solve real exercises with AI feedback — free to start.

Try it free →