SQL
All Top 50 SQL Interview Questions#39
Traverse Organizational Hierarchy with Recursive CTEs in SQL
HardPwCInterview Question #39
Asked at PwCGiven `employees` (emp_id, name, manager_id), write a recursive CTE to output each employee, their management depth level (CEO = 1, their direct reports = 2, etc.), and their full breadcrumb reporting path.
Input Table: employees
3 rows preview| emp_id | name | manager_id |
|---|---|---|
| 1 | Rajesh | NULL |
| 2 | Kaushal | 1 |
| 3 | Ankit | 2 |
Expected Output Structure3 rows
| emp_id | name | level | path |
|---|---|---|---|
| 1 | Rajesh | 1 | Rajesh |
| 2 | Kaushal | 2 | Rajesh -> Kaushal |
| 3 | Ankit | 3 | Rajesh -> Kaushal -> Ankit |
Interview Context
Asked frequently in data analyst and business analyst technical rounds. Focus on clean filtering, optimal indexing usage, and unambiguous column selection.
PostgreSQL 15
Ready to execute
Click "Run Query" or press Ctrl + Enter to test your query.
Output will be verified against the test dataset.