Hard JOINsSubqueriesCTEs Premium

SQL interview question: Org Chart Hierarchy With a Recursive CTE

Full Organizational Hierarchy Depth

The enterprise team needs a complete organizational chart showing each employee's full reporting chain up to the CEO.

Write a recursive CTE to show every employee with their level in the organization (top executives = level 1, direct reports = level 2, etc.).

Return employee_id, employee_name (full name), org_level, and reports_to_chain (e.g., "Alice Chen -> Sarah Johnson"). Order by org_level, then employee_id, and return the first 15.

Skills: recursive CTEs for hierarchical data traversal

Tables

employees 37 rows
  • id integer PK
  • first_name text
  • last_name text
  • email text
  • department_id integer → departments
  • salary integer
  • hire_date text
  • manager_id integer → employees
  • title text
idfirst_namelast_nameemaildepartment_idsalaryhire_datemanager_idtitle
1AliceChen[email protected]12500002015-01-15NULLCEO
2RobertMartinez[email protected]21800002016-03-20NULLCEO
3SarahJohnson[email protected]11500002017-06-101VP Engineering

Keep going