Predict the output
Walk the reporting chain under the CEO. What's printed?
CREATE TABLE staff (id int, boss int, name text);
INSERT INTO staff VALUES
(1, NULL, 'ceo'), (2, 1, 'cto'), (3, 2, 'dev'), (4, 1, 'cfo');
WITH RECURSIVE tree AS (
SELECT id, name, 0 AS depth FROM staff WHERE boss IS NULL
UNION ALL
SELECT s.id, s.name, t.depth + 1
FROM staff s JOIN tree t ON s.boss = t.id
)
SELECT max(depth) FROM tree;Hint 1 of 1
Count the hops from the CEO to the dev.
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 2
Correct. ceo (0) → cto (1) → dev (2).
WITH RECURSIVE starts at the CEO with depth 0 and adds one level per join. The deepest chain is ceo, cto, dev, so the maximum depth is 2.
Why not the others?
- B
3. Depth starts at 0 for the CEO. - C
1. dev is two levels below the CEO. - D
4. That's the number of rows.
| max |
|---|
| 2 |
(1 row)