← All SQL interview questions
Build each employee's reporting chain to the CEO
HardRecursive CTEsTargetOracle
An access-review tool must display the full escalation chain for each person.
org_members stores reports_to as a self-reference; the CEO's is NULL. Using a recursive CTE, return member_id, member_name, levels_from_top (0 for the CEO) and chain — the names from the CEO down to that member joined with -> .
Sample data
Table: org_members
15 row(s) · showing first 8
| member_idINT | member_nameTEXT | titleTEXT | reports_toINT |
|---|---|---|---|
| 1 | Radhika Anand | CEO | NULL |
| 2 | Aakash Verma | VP Data | 1 |
| 3 | Kavya Reddy | VP Engineering | 1 |
| 4 | Vikram Chandra | Director Analytics | 2 |
| 5 | Zoya Mirza | Director Science | 2 |
| 6 | Simran Kaur | Director Platform | 3 |
| 7 | Nandini Bose | Analytics Manager | 4 |
| 8 | Imran Shaikh | Analytics Manager | 4 |
org_members
- member_idINT
- member_nameTEXT
- titleTEXT
- reports_toINT
- Step 1: Anchor on the top of the hierarchy: the row where `reports_to IS NULL` starts at level 0 with a chain containing only its own name.
- Step 2: In the recursive member, join `org_members` to the CTE on `c.member_id = m.reports_to` so each pass picks up the direct reports of everyone found so far.
- Step 3: Increment `levels_from_top` by 1 per hop and append the name to `chain` with the `||` string concatenation operator.
- Step 4: `UNION ALL` (not `UNION`) keeps the recursion cheap and preserves every distinct path; Postgres stops when an iteration adds no rows.
- Step 5: Select all four columns from the CTE. Every member appears exactly once because each has at most one parent.
WITH RECURSIVE chain_cte AS (
SELECT member_id,
member_name,
0 AS levels_from_top,
member_name AS chain
FROM org_members
WHERE reports_to IS NULL
UNION ALL
SELECT m.member_id,
m.member_name,
c.levels_from_top + 1,
c.chain || ' -> ' || m.member_name
FROM org_members AS m
INNER JOIN chain_cte AS c ON c.member_id = m.reports_to
)
SELECT member_id, member_name, levels_from_top, chain
FROM chain_cte;Learn the concept first
Stuck on Recursive CTEs? These free SQL lessons teach it step by step.
More Recursive CTEs questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program