appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Recursive queries and hierarchies

Lesson 3 of 411 minAdvanced

Walk trees and graphs, such as org charts and category trees, with WITH RECURSIVE.

Some data is a tree: employees and their managers, categories and subcategories. A recursive CTE lets one query follow those links to any depth.

All reports below manager 1
WITH RECURSIVE team AS (
  SELECT id, name, manager_id, 0 AS depth
  FROM employees
  WHERE id = 1
  UNION ALL
  SELECT e.id, e.name, e.manager_id, t.depth + 1
  FROM employees e
  JOIN team t ON e.manager_id = t.id
)
SELECT * FROM team ORDER BY depth, name;

The two parts

  • The anchor (before UNION ALL) is the starting row or rows.
  • The recursive step (after it) joins the table to the rows found so far and adds the next level. It repeats until it finds no new rows.

CarefulIf the data has a cycle (A reports to B and B to A), the recursion never ends. Add a depth limit such as WHERE t.depth < 20, or track visited ids, to protect yourself.

NoteOracle and SQL Server use slightly different syntax (WITH without the word RECURSIVE in SQL Server, CONNECT BY in Oracle). MySQL supports WITH RECURSIVE from version 8.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What are the two parts of a recursive CTE?
2. What can make a recursive query run forever?
3. Which column in the example tracks how deep each row is in the tree?

Key terms