Loading...
Loading...
You are working with a company's HR database and need to identify employees who are earning a higher salary than the manager they directly report to. This is a classic SQL self-join problem that tests your ability to query hierarchical data within a single table.
You are given a single table called Employee with the following structure:
| Column Name | Type | Description |
|---|---|---|
| id | int | Primary key, unique employee identifier |
| name | varchar | Employee's full name |
| salary | int | Employee's annual salary |
| managerId | int | Foreign key referencing the id of their manager (NULL if no manager) |
Write a SQL query to find the names of all employees who earn strictly more than their direct manager. Return the result in any order.
Input: The Employee table as described above.
Output: A result set with a single column Employee containing the names of qualifying employees.
Employee Table:
| id | name | salary | managerId |
|---|---|---|---|
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
Output:
| Employee |
|---|
| Joe |
Explanation: Joe (salary: 70000) reports to Sam (salary: 60000). Since 70000 > 60000, Joe qualifies. Henry (salary: 80000) reports to Max (salary: 90000). Since 80000 < 90000, Henry does NOT qualify.
Self-Join Approach: Join the Employee table with itself — once as the employee (e1) and once as the manager (e2) — matching on e1.managerId = e2.id. Then filter rows where e1.salary > e2.salary.
Subquery Approach: For each employee who has a manager, use a correlated subquery to fetch their manager's salary and compare.
Key Considerations:
- The `Employee` table may have 0 to 10,000 rows. - `id` is unique and non-null. - `salary` values are in the range `[1000, 1,000,000]`. - `managerId` is either NULL or a valid `id` within the same table. - No circular management chains (an employee cannot be their own manager, directly or indirectly). - Employee names are non-empty strings of up to 50 characters.
NULL managerId (they have no manager and should be excluded).Employee.Recommended approach: The self-join is generally more efficient and cleaner for this problem.