How would you solve the Employee Hierarchy problem using a recursive CTE or repeated self-joins to build each employee’s reporting chain or count subordinates?
💡 Model Answer
To solve the Employee Hierarchy problem, you can use a recursive Common Table Expression (CTE) in SQL. The CTE starts with the root employees (those with NULL manager_id) and recursively joins the employee table to itself on the manager_id = employee_id relationship. Each recursion level adds one level of the reporting chain. For example: WITH RECURSIVE hierarchy AS (SELECT employee_id, employee_name, manager_id, 0 AS level FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.employee_id, e.employee_name, e.manager_id, h.level + 1 FROM employees e JOIN hierarchy h ON e.manager_id = h.employee_id) SELECT FROM hierarchy; This returns every employee with their depth in the hierarchy. To count subordinates, you can aggregate the recursive result: SELECT manager_id, COUNT() AS subordinates FROM hierarchy GROUP BY manager_id; Recursive CTEs are efficient for moderate depth trees and are supported by most modern RDBMS. For very deep hierarchies, consider materialized path or adjacency list with pre‑computed paths.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500