You are given an Employees table representing the company hierarchy. Each employee has an ID, name, and their direct manager's ID.
Write a SQL solution to find all employees that directly or indirectly report to the head of the company (employee_id = 1).
Key Points:
- Direct reporting: Employee → Manager
- Indirect reporting: Employee → Manager → Manager's Manager (up to 3 levels)
- The head of company has employee_id = 1
- Maximum hierarchy depth is 3 managers
Table Schema
| Column Name | Type | Description |
|---|---|---|
employee_id
PK
|
int | Unique employee identifier |
employee_name
|
varchar | Employee's full name |
manager_id
|
int | ID of direct manager (NULL for head) |
Input & Output
| employee_id | employee_name | manager_id |
|---|---|---|
| 1 | Boss | |
| 2 | Alice | 1 |
| 3 | Bob | 2 |
| 4 | Charlie | 2 |
| 5 | David | 3 |
| employee_id |
|---|
| 2 |
| 3 |
| 4 |
| 5 |
Boss (ID=1) is the head. Alice (ID=2) reports directly to Boss. Bob and Charlie (ID=3,4) report to Alice, so indirectly to Boss. David (ID=5) reports to Bob, so indirectly to Boss through 2 levels.
| employee_id | employee_name | manager_id |
|---|---|---|
| 1 | Boss | |
| 2 | Alice | 1 |
| 3 | Bob | 1 |
| employee_id |
|---|
| 2 |
| 3 |
Simple case where Alice and Bob both report directly to the head (Boss). No indirect reporting levels exist.
| employee_id | employee_name | manager_id |
|---|---|---|
| 1 | Boss | |
| 2 | Alice | 1 |
| 7 | Eve | 6 |
| 6 | Frank |
| employee_id |
|---|
| 2 |
Only Alice reports to Boss (ID=1). Eve reports to Frank (ID=6) who is a separate head, so Eve is not included in the results.
Constraints
-
1 ≤ employee_id ≤ 2000 -
employee_idis unique for each employee -
manager_idis NULL only for company heads - Hierarchy depth will not exceed 3 levels below head