Interview Questions/SQL/Full Ancestor Chain Per Employee

Full Ancestor Chain Per Employee

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

Medium

Description

You are given a Staff table representing a management hierarchy. Write a SQL query that, for every non-root employee, lists each of their ancestors (managers up the chain to the root) along with how many levels above that ancestor is. Return (employee_id, employee_name, ancestor_id, ancestor_name, levels_above) ordered by employee_id, then levels_above. Do NOT include the root employee in the output (they have no ancestors). Root employees also should not appear as an employee row. Table: Staff

Column NameTypeDescription
idINTPrimary key
nameVARCHAREmployee name
manager_idINTNULL if this is the root

Database Schema (Inferred)

Staff

Column NameExample Value
id1
nameCEO
manager_idNULL

Example

Staff

idnamemanager_id
1CEONULL
2VP_Eng1
3VP_Sales1
4Manager_A2
5Manager_B2
6Engineer_X4
7Engineer_Y4
8Sales_Rep3

Output

employee_idemployee_nameancestor_idancestor_namelevels_above
2VP_Eng1CEO1
3VP_Sales1CEO1
4Manager_A2VP_Eng1
4Manager_A1CEO2
5Manager_B2VP_Eng1
5Manager_B1CEO2
6Engineer_X4Manager_A1
6Engineer_X2VP_Eng2
6Engineer_X1CEO3
7Engineer_Y4Manager_A1
7Engineer_Y2VP_Eng2
7Engineer_Y1CEO3
8Sales_Rep3VP_Sales1
8Sales_Rep1CEO2

Explanation:

Anchor: every non-root employee paired with their direct manager. Recurse: keep climbing to the manager's manager, incrementing level each time, until reaching the root.

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...

Staff

idnamemanager_id
1CEONULL
2VP_Eng1
3VP_Sales1
4Manager_A2
5Manager_B2
6Engineer_X4
7Engineer_Y4
8Sales_Rep3

Output

employee_idemployee_nameancestor_idancestor_namelevels_above
2VP_Eng1CEO1
3VP_Sales1CEO1
4Manager_A2VP_Eng1
4Manager_A1CEO2
5Manager_B2VP_Eng1
5Manager_B1CEO2
6Engineer_X4Manager_A1
6Engineer_X2VP_Eng2
6Engineer_X1CEO3
7Engineer_Y4Manager_A1
7Engineer_Y2VP_Eng2
7Engineer_Y1CEO3
8Sales_Rep3VP_Sales1
8Sales_Rep1CEO2