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

Employee Hierarchy Depth & Subordinate Salary

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

Examples

Example 1

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.

query.sql