Overview
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
Short Course
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
Task
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.
Database
Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.
| idINTEGER | nameTEXT | manager_idINTEGER |
|---|---|---|
| 1 | Ada | NULL |
| 2 | Ben | 1 |
| 3 | Cleo | 1 |
| 4 | Dan | 2 |
| 5 | Eve | 4 |
| 6 | Finn | NULL |
| 7 | Gus | 6 |
Test Suites
Pending
Next
Output