Interview Questions/SQL/Employee Hierarchy Depth & Subordinate Salary

Employee Hierarchy Depth & Subordinate Salary

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. Write a SQL query to find, for each employee: - Their depth in the org hierarchy (root = 0) - The total salary of ALL employees under them (direct + indirect reports only, excluding themselves) Return (id, name, depth, total_reports_salary) ordered by id. Table: Employees

Column NameTypeDescription
idINTPrimary key
nameVARCHAREmployee name
manager_idINTNULL if top of hierarchy
salaryINTEmployee salary
departmentVARCHARDepartment name

Database Schema (Inferred)

Employees

Column NameExample Value
id1
nameAlice
manager_idNULL
salary10000
departmentEngineering

Example

Employees

idnamemanager_idsalarydepartment
1AliceNULL10000Engineering
2Bob18000Engineering
3Carol17000Engineering
4Dave25000Engineering
5Eve24500Engineering
6Frank36000Engineering

Output

idnamedepthtotal_reports_salary
1Alice030500
2Bob19500
3Carol16000
4Dave20
5Eve20
6Frank20

Explanation:

Use a recursive CTE to traverse the hierarchy and compute depth. Use a second recursive CTE (subtree) to explode all descendants of every node. Subtract the root's own salary from the subtree total to get reports-only salary. Leaf nodes have 0.

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_idsalarydepartment
1AliceNULL10000Engineering
2Bob18000Engineering
3Carol17000Engineering
4Dave25000Engineering
5Eve24500Engineering
6Frank36000Engineering

Output

idnamedepthtotal_reports_salary
1Alice030500
2Bob19500
3Carol16000
4Dave20
5Eve20
6Frank20