CEO Subordinate Hierarchy
Imagine you're working at a company and need to build a complete organizational chart showing everyone who reports to the CEO, either directly or indirectly. This is a classic hierarchical tree traversal problem that tests your understanding of recursive relationships in databases.
You have an Employees table where each employee has a manager (except the CEO who has NULL as manager_id). Your task is to:
- Find all subordinates of the CEO at any level
- Calculate their hierarchy level (1 for direct reports, 2 for their reports, etc.)
- Compute salary differences from the CEO's salary
- Order results by hierarchy level, then by employee ID
This problem combines recursive tree traversal with salary analysis, making it perfect for testing your SQL skills with Common Table Expressions (CTEs) and recursive queries.
Example: If Alice (CEO) manages Bob and Charlie, and Bob manages David, then David has hierarchy_level = 2 and salary_difference = David's salary - Alice's salary.
Input & Output
Constraints
- 1 โค employees.length โค 1000
- employee_id is unique for each employee
- Exactly one employee has manager_id = NULL (the CEO)
- All manager_id values (except CEO) reference valid employee_id
- 1 โค salary โค 106
- No circular management relationships exist