InterviewPrepKit

Home / SQL / Subqueries & CTEs

Org Chart Depth With a Recursive CTE

medium
Solving tips
  • A recursive CTE has two parts joined by `UNION ALL`: an anchor member (the starting rows) and a recursive member that references the CTE by name to walk one level further each iteration.
  • For an org chart, anchor on the top employee (`manager_id IS NULL`) at level 1, then join employees to their manager's already-computed row and add 1 to the level.
  • Recursion stops naturally when the recursive member returns no new rows; a genuine cycle in the data would loop forever unless you guard against it.

Given a self-referencing employee table where each person points to their manager, compute the depth of every employee in the org chart. The top of the org is at level 1.

Schema

CREATE TABLE employees (
    id         integer PRIMARY KEY,
    name       text    NOT NULL,
    manager_id integer REFERENCES employees(id)   -- NULL for the top of the org
);

Sample data — employees:

idnamemanager_id
1AliceNULL
2Bob1
3Carol1
4Dave2
5Eve2
6Frank3
7Grace4

Task

Return each employee’s name and their level in the hierarchy, where the top employee (no manager) is level 1, their direct reports are level 2, and so on.

Order by level ascending, then by name ascending. Expected columns: name, level.

Expected output

Alice is the top (level 1). Bob and Carol report to Alice (level 2). Dave and Eve report to Bob, and Frank reports to Carol (level 3). Grace reports to Dave (level 4).

namelevel
Alice1
Bob2
Carol2
Dave3
Eve3
Frank3
Grace4
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.