Recursive queries and hierarchies
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.
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.