LeetCode 1978. Employees Whose Manager Left the Company SQL Solution
Problem
LeetCode SQL Problem
- Employees Whose Manager Left the Company
Employees table
employee_id | name | manager_id | salary |
---|---|---|---|
3 | Mila | 9 | 60301 |
12 | Antonella | null | 31000 |
13 | Emery | null | 67084 |
1 | Kalel | 11 | 21241 |
9 | Mikaela | null | 50937 |
11 | Joziah | 6 | 28485 |
Solution - Self Join + Left Join
- MySQL
- TSQL
SELECT E.employee_id
FROM Employees AS E
LEFT JOIN Employees AS M ON E.manager_id = M.employee_id
WHERE E.salary < 30000
AND E.manager_id IS NOT NULL
AND M.employee_id IS NULL
SELECT E.employee_id
FROM Employees AS E
LEFT JOIN Employees AS M ON E.manager_id = M.employee_id
WHERE E.salary < 30000
AND E.manager_id IS NOT NULL
AND M.employee_id IS NULL
The above SQL query selects the employee IDs of employees who have a salary less than 30,000 and have a manager, but their manager is not present in the Employees table.
Let's break the SQL down step by step:
-
SELECT E.employee_id
: This selects the employee IDs of the employees we're interested in. -
FROM Employees AS E
: This specifies the table we're selecting from, which is the Employees table, and assigns it an alias of "E". -
LEFT JOIN Employees AS M ON E.manager_id = M.employee_id
: This joins the Employees table to itself using a left join. The join condition is that the manager ID of the employee in table E matches the employee ID in table M. This will create a table where each row represents an employee, and the corresponding row (if any) from the Employees table where that employee's manager ID matches the manager's employee ID. -
WHERE E.salary < 30000
: This filters the results to only include employees with a salary less than 30000. -
AND E.manager_id IS NOT NULL
: This adds another filter, requiring that the employee has a manager (i.e., their manager ID is not null). -
AND M.employee_id IS NULL
: This final filter requires that the corresponding row from the Employees table (i.e., the row representing the employee's manager) is null. This means that the employee does not have a manager in the Employees table, so their manager is not present in the table.
The overall effect of this SQL query is to find employees with a salary less than 30000 who have a manager, but whose manager is not present (left the company) in the Employees table.
Query Output
employee_id |
---|
11 |