SQL · Level 3 CTEs

SQL Recursive CTEs

List everyone who reports to a manager, directly or not, with WITH RECURSIVE, and track how deep each person is in the org chart.

  • WITH RECURSIVE
  • Starting rows UNION ALL the next level
  • A condition that ends the recursion

WITH RECURSIVE runs a starting query, then repeats a second query on the rows found so far, which is how you walk a tree like an org chart. Trap: the repeated part must eventually find no new rows, or the query never ends.

WITH RECURSIVE n(x) AS (
  SELECT 1
  UNION ALL
  SELECT x + 1 FROM n WHERE x < 5   -- this WHERE stops it
)
SELECT x FROM n;   -- 1, 2, 3, 4, 5

Return everyone who reports to Ada (id 1), directly or through other managers: their name and depth (1 = reports to Ada directly), ordered by depth, then name. In the database below, Eve is 3 levels below Ada.

Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.

employees 7 rows
idINTEGERnameTEXTmanager_idINTEGER
1AdaNULL
2Ben1
3Cleo1
4Dan2
5Eve4
6FinnNULL
7Gus6
solution.sql
Test Suites Pending
Output