Interview Questions/SQL/Employee Hierarchy Depth (Recursive CTE)

Employee Hierarchy Depth (Recursive CTE)

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given an Employees table where each employee may have a manager. The CEO has no manager (manager_id is NULL). Write a SQL query using a recursive CTE to compute the hierarchy depth of every employee. The CEO has depth 0, direct reports have depth 1, their reports have depth 2, and so on. Return id, name, and depth for all employees, ordered by id. Table: Employees

Column NameTypeDescription
idINTPrimary key
nameVARCHAREmployee name
manager_idINTID of the manager (NULL for the root)

Database Schema (Inferred)

Employees

Column NameExample Value
id1
nameCEO
manager_idNULL

Example

Employees

idnamemanager_id
1CEONULL
2VP11
3VP21
4Mgr12
5Mgr22
6Mgr33
7Emp14
8Emp24
9Emp36

Output

idnamedepth
1CEO0
2VP11
3VP21
4Mgr12
5Mgr22
6Mgr32
7Emp13
8Emp23
9Emp33

Explanation:

Start with the root (manager_id IS NULL) at depth 0. Each recursive step increases depth by 1 for all direct reports.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Employees

idnamemanager_id
1CEONULL
2VP11
3VP21
4Mgr12
5Mgr22
6Mgr33
7Emp14
8Emp24
9Emp36

Output

idnamedepth
1CEO0
2VP11
3VP21
4Mgr12
5Mgr22
6Mgr32
7Emp13
8Emp23
9Emp33