Employees With Missing Information Problem
Description
LeetCode Problem 1965.
Table: Employees
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| employee_id | int |
| name | varchar |
+-------------+---------+
employee_id is the primary key for this table.
Each row of this table indicates the name of the employee whose ID is employee_id.
Table: Salaries
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| employee_id | int |
| salary | int |
+-------------+---------+
employee_id is the primary key for this table.
Each row of this table indicates the salary of the employee whose ID is employee_id.
Write an SQL query to report the IDs of all the employees with missing information. The information of an employee is missing if:
- The employee's name is missing, or
- The employee's salary is missing.
Return the result table ordered by employee_id in ascending order.
The query result format is in the following example:
Employees table:
+-------------+----------+
| employee_id | name |
+-------------+----------+
| 2 | Crew |
| 4 | Haven |
| 5 | Kristian |
+-------------+----------+
Salaries table:
+-------------+--------+
| employee_id | salary |
+-------------+--------+
| 5 | 76071 |
| 1 | 22517 |
| 4 | 63539 |
+-------------+--------+
Result table:
+-------------+
| employee_id |
+-------------+
| 1 |
| 2 |
+-------------+
Employees 1, 2, 4, and 5 are working at this company.
The name of employee 1 is missing.
The salary of employee 2 is missing.
Solution
Approach: Two Anti-Joins and UNION
An employee's information is missing when their id appears in only one of the two tables. That gives two cases, and each is a simple anti-join:
- No salary: ids in
Employeesthat areNOT INSalaries. - No name: ids in
Salariesthat areNOT INEmployees.
UNION the two lists and sort by employee_id. The ORDER BY at the end applies to the combined result.
This is the job a FULL OUTER JOIN would do (keep rows with no match on either side), but MySQL does not support FULL OUTER JOIN, so the two directions are written separately.
NOT IN is safe here because employee_id is the primary key of both tables and can never be NULL. If the subquery could return a NULL, NOT IN would never be true and that branch would return no rows.
The Pandas version uses isin for the same two checks, concatenates the ids and sorts them.
-- Has a name but no salary.
SELECT employee_id
FROM Employees
WHERE employee_id NOT IN (SELECT employee_id FROM Salaries)
UNION
-- Has a salary but no name.
SELECT employee_id
FROM Salaries
WHERE employee_id NOT IN (SELECT employee_id FROM Employees)
ORDER BY employee_id;