Given an Employees table with employee information including their manager relationships, write a SQL query to find all subordinates of the CEO (both direct and indirect).
The CEO is identified as the employee with manager_id = NULL.
Requirements:
subordinate_id: The employee_id of the subordinatesubordinate_name: The name of the subordinatehierarchy_level: The level in hierarchy (1 for direct reports, 2 for their reports, etc.)salary_difference: Difference between subordinate's salary and CEO's salary
Return results ordered by hierarchy_level ascending, then by subordinate_id ascending.
Table Schema
| Column Name | Type | Description |
|---|---|---|
employee_id
PK
|
int | Unique identifier for each employee |
employee_name
|
varchar | Name of the employee |
manager_id
|
int | Employee ID of the manager (NULL for CEO) |
salary
|
int | Employee's salary |
Input & Output
| employee_id | employee_name | manager_id | salary |
|---|---|---|---|
| 1 | Alice | 150000 | |
| 2 | Bob | 1 | 120000 |
| 3 | Charlie | 1 | 110000 |
| 4 | David | 2 | 105000 |
| 5 | Eve | 2 | 100000 |
| 6 | Frank | 3 | 95000 |
| 7 | Grace | 3 | 98000 |
| 8 | Helen | 5 | 90000 |
| subordinate_id | subordinate_name | hierarchy_level | salary_difference |
|---|---|---|---|
| 2 | Bob | 1 | -30000 |
| 3 | Charlie | 1 | -40000 |
| 4 | David | 2 | -45000 |
| 5 | Eve | 2 | -50000 |
| 6 | Frank | 2 | -55000 |
| 7 | Grace | 2 | -52000 |
| 8 | Helen | 3 | -60000 |
Alice is the CEO (manager_id = NULL). Bob and Charlie report directly to Alice (level 1). David and Eve report to Bob, Frank and Grace report to Charlie (level 2). Helen reports to Eve (level 3). All salary differences are calculated relative to Alice's salary of 150000.
| employee_id | employee_name | manager_id | salary |
|---|---|---|---|
| 1 | CEO | 200000 | |
| 2 | Manager1 | 1 | 120000 |
| 3 | Manager2 | 1 | 130000 |
| subordinate_id | subordinate_name | hierarchy_level | salary_difference |
|---|---|---|---|
| 2 | Manager1 | 1 | -80000 |
| 3 | Manager2 | 1 | -70000 |
Simple case with CEO having two direct reports. Both managers are at hierarchy level 1 with negative salary differences compared to the CEO's 200000 salary.
| employee_id | employee_name | manager_id | salary |
|---|---|---|---|
| 1 | OnlyEmployee | 100000 |
| subordinate_id | subordinate_name | hierarchy_level | salary_difference |
|---|
Edge case where there's only one employee who is the CEO. Since they have no subordinates, the result is empty.
Constraints
-
1 ≤ employee_id ≤ 2000 -
1 ≤ employee_name.length ≤ 15 -
1 ≤ salary ≤ 10^6 -
There is exactly one CEO (employee with
manager_id = NULL) - All manager_id values (except CEO) reference valid employee_id values