Employee Bonus Problem
Description
LeetCode Problem 577.
Select all employee's name and bonus whose bonus is < 1000.
Table:Employee
+-------+--------+-----------+--------+
| empId | name | supervisor| salary |
+-------+--------+-----------+--------+
| 1 | John | 3 | 1000 |
| 2 | Dan | 3 | 2000 |
| 3 | Brad | null | 4000 |
| 4 | Thomas | 3 | 4000 |
+-------+--------+-----------+--------+
empId is the primary key column for this table.
Table: Bonus
+-------+-------+
| empId | bonus |
+-------+-------+
| 2 | 500 |
| 4 | 2000 |
+-------+-------+
empId is the primary key column for this table.
Example ouput:
+-------+-------+
| name | bonus |
+-------+-------+
| John | null |
| Dan | 500 |
| Brad | null |
+-------+-------+
Solution
Approach: LEFT JOIN and NULL Check
Employees without a row in Bonus must be in the result too (John and Brad, with a null bonus), so start from Employee and attach the bonus with a LEFT JOIN. An employee without a bonus gets NULL in b.bonus.
The detail people get wrong is the filter. WHERE b.bonus < 1000 alone drops those employees: comparing NULL with a number gives NULL, not true, so the row is filtered out. Add OR b.bonus IS NULL to keep them.
An inner join would have the same problem, since it removes employees without a bonus before the filter even runs.
The Pandas version left-merges employee with bonus and keeps the rows where bonus < 1000 or bonus is missing (isna()).
SELECT e.name,
b.bonus
FROM Employee AS e
LEFT JOIN Bonus AS b
ON b.empId = e.empId
WHERE b.bonus < 1000
OR b.bonus IS NULL; -- employees without a bonus