Departments With No Employees
Return the name of every department that has no employees at
all.
Order by name.
A warning. The shortest answer here is
WHERE id NOT IN (SELECT department_id FROM employee), and it returns
zero rows against this data. Finding out why is the problem.
Expected output
name
--------
Archive
Research
Editorial
Two departments have nobody in them: Research and Archive. Three ways to say so, and one way to get it wrong.
The wrong one
SELECT d.name
FROM department d
WHERE d.id NOT IN (SELECT department_id FROM employee)
ORDER BY d.name;
Zero rows. The subquery returns
{1,1,2,2,3,NULL}, and NOT IN expands to a chain of
inequalities:
d.id <> 1 AND d.id <> 1 AND ... AND d.id <> NULL
That last term is unknown, and true AND unknown is
unknown. WHERE keeps only rows where the condition is true,
so nothing survives. One NULL in the subquery disables the whole predicate.
This is the single most common NULL bug in production SQL, and it is invisible until the first null arrives — the query works perfectly while every employee has a department.
NOT EXISTS, the one to reach for
SELECT d.name
FROM department d
WHERE NOT EXISTS (
SELECT 1 FROM employee e WHERE e.department_id = d.id
)
ORDER BY d.name;
It asks about the existence of rows rather than comparing values, so
a NULL department_id simply fails to match d.id and
contributes nothing. Correct regardless of nullability, which means it stays
correct when a migration makes a column nullable.
The outer-join anti-join
SELECT d.name
FROM department d
LEFT JOIN employee e ON e.department_id = d.id
WHERE e.id IS NULL
ORDER BY d.name;
Equally correct, and the form to use when you also want columns from the
preserved side. Note the test is on e.id — the right table's
primary key, which can only be NULL when nothing matched. Testing a nullable
column instead would conflate "no match" with "matched a row whose value is
null".
EXCEPT
SELECT name FROM department
WHERE id IN (SELECT id FROM department EXCEPT SELECT department_id FROM employee)
ORDER BY name;
Also null-safe, because set operations compare rows rather than evaluating a predicate per value. Cleanest when you want only the key.
What an interviewer is checking
Whether you know that NOT IN and NOT EXISTS are not
interchangeable. The follow-up is usually "what if the column were
NOT NULL?" — in which case NOT IN is fine and the
planner treats the two almost identically. The point is knowing which
assumption you are relying on.
department
5 rows
| idinteger | nametext |
|---|---|
| 1 | Engineering |
| 2 | Sales |
| 3 | Support |
| 4 | Research |
| 5 | Archive |
employee
6 rows
| idinteger | nametext | department_idinteger |
|---|---|---|
| 1 | Alice | 1 |
| 2 | Bob | 1 |
| 3 | Carol | 2 |
| 4 | Dan | 2 |
| 5 | Erin | 3 |
Showing 5 of 6 rows.