Skip to content
Onsite

All reports under a manager with a recursive CTE

MediumP2Coding

Table employee:

ColumnType
idint (primary key)
nametext
manager_idint (NULL for the top)

List everyone who reports to employee 1, directly or indirectly, with their depth: 1 for a direct report, 2 for a report of a report, and so on.

The data should be a tree, but it may contain a cycle by mistake (A manages B, B manages C, C manages A). Your query must still terminate, and must never list employee 1 itself.

Output columns: id, name, depth. Order by depth, then id.

Schema

CREATE TABLE employee (
  id int PRIMARY KEY,
  name text NOT NULL,
  manager_id int
);

Example 1

Input
employee: (1, Ann, NULL), (2, Bob, 1), (3, Cy, 2)
Output
(2, Bob, 1), (3, Cy, 2)

Constraints

  • PostgreSQL dialect.

Hints

PostgreSQL
Run checks the 3 visible tests, Submit all 6.