Sub topic 3
The NOT IN Trap and the NOT EXISTS Fix
This chapter assumes you know SELECT, WHERE, joins, GROUP BY, subqueries, and the NULL basics from earlier chapters. It uses the same employees table.
The NOT IN Trap and the NOT EXISTS Fix
NOT IN returns a row only when the test is TRUE for every value in the list. If the list contains NULL, that comparison is UNKNOWN, so no row passes.
-- Returns no rows, because manager_id contains a NULL.
SELECT name FROM employees
WHERE id NOT IN (SELECT manager_id FROM employees);NOT EXISTS checks for matching rows and is not affected by the NULL:
-- Returns Cy and Di, the employees who manage nobody.
SELECT e.name FROM employees e
WHERE NOT EXISTS (
SELECT 1 FROM employees m WHERE m.manager_id = e.id
);NULL Keys, Outer Joins, and Anti-Joins
A LEFT JOIN fills unmatched right-side columns with NULL. Testing a column that is never NULL in a matched row, such as the primary key, finds the rows with no match. This pattern is an anti-join.
SELECT e.name
FROM employees e
LEFT JOIN employees m ON m.manager_id = e.id
WHERE m.id IS NULL;Rows with a NULL join key match nothing, so an inner join silently drops them.
NULL in GROUP BY, DISTINCT, and UNION
Grouping and duplicate removal treat all NULLs as equal, unlike comparisons. GROUP BY places NULLs in one group. DISTINCT and UNION keep one NULL row. UNION ALL keeps every row.
Sorting NULLs: NULLS FIRST and NULLS LAST
The default position of NULLs in ORDER BY depends on the database. State the position explicitly:
SELECT name, commission
FROM employees
ORDER BY commission DESC NULLS LAST;Constraints: NOT NULL, UNIQUE, and CHECK
- NOT NULL rejects NULL values.
- UNIQUE does not treat NULLs as equal, so most systems allow several NULLs.
- CHECK fails only when its condition is FALSE. An UNKNOWN result passes, so
CHECK (commission >= 0)accepts a NULL commission.
Design Choices: When to Allow NULL
Allow NULL only when "no value" is a real state, such as an employee with no manager. If a missing value has a fixed meaning, use a DEFAULT instead. If a value can be absent many times over, store it in a separate table.
Where Database Systems Differ
- The default sort position of NULLs differs between systems.
- SQL Server allows only one NULL in a UNIQUE column. PostgreSQL and SQLite allow many.
- NULLS FIRST and NULLS LAST work in PostgreSQL, Oracle, and SQLite 3.30 and later. MySQL does not support them.
Exercise
Which query returns the employees who have no direct reports, and why is the other one wrong? Use WHERE id NOT IN (SELECT manager_id FROM employees) as the alternative.
Show answer
Use WHERE NOT EXISTS (SELECT 1 FROM employees m WHERE m.manager_id = e.id). The NOT IN version returns no rows, because the subquery returns a NULL manager_id for Ada.