Sub topic 10
NULL Keys, Outer Joins, and Anti-Joins
Assume you know basic JOIN, WHERE, and GROUP BY. This chapter focuses on how missing join keys change matching and how to find rows without matches.
NULL Does Not Match NULL
A join condition such as a.key = b.key is a comparison. If either key is NULL, the result is UNKNOWN, not TRUE. Therefore, two rows with NULL in their keys do not match in an ordinary equi-join.
Using the sample employees table, Ada has no manager because manager_id is NULL:
SELECT e.name, m.name AS manager_name
FROM employees AS e
JOIN employees AS m
ON m.id = e.manager_id;This inner join returns Ben, Cy, and Di. Ada is removed because NULL = 1 is UNKNOWN, so the join condition is not true.
Preserving Rows with a LEFT JOIN
A LEFT JOIN keeps every row from its left input. If no right-side row matches, SQL fills the right-side columns with NULL.
SELECT e.name, m.name AS manager_name
FROM employees AS e
LEFT JOIN employees AS m
ON m.id = e.manager_id;This query also returns Ada, with manager_name set to NULL.
The location of a filter matters. This query keeps employees whose manager is Ben, but it removes employees without a manager because the WHERE clause runs after the outer join:
SELECT e.name, m.name AS manager_name
FROM employees AS e
LEFT JOIN employees AS m
ON m.id = e.manager_id
WHERE m.name = 'Ben';To preserve employees without managers while restricting matched managers, put the condition in ON:
SELECT e.name, m.name AS manager_name
FROM employees AS e
LEFT JOIN employees AS m
ON m.id = e.manager_id
AND m.name = 'Ben';Anti-Joins: Finding Rows Without a Match
An anti-join returns rows from one table for which no related row exists. A reliable pattern uses LEFT JOIN and tests a right-side column that cannot be NULL for a real match, such as a primary key:
SELECT e.name
FROM employees AS e
LEFT JOIN employees AS report
ON report.manager_id = e.id
WHERE report.id IS NULL;This returns Cy and Di because they manage no employees. It does not test report.manager_id; that column could legitimately contain NULL in other data. Test the right table's non-null primary key instead.
NOT EXISTS expresses the same intent directly:
SELECT e.name
FROM employees AS e
WHERE NOT EXISTS (
SELECT 1
FROM employees AS report
WHERE report.manager_id = e.id
);Prefer NOT EXISTS when the relationship is naturally described as “no matching row.” It is also safe when the subquery can return NULL.
Why NOT IN Is Dangerous
NOT IN compares against every value in its list. If that list contains NULL, the comparison can become UNKNOWN, so the query may return no rows:
SELECT e.name
FROM employees AS e
WHERE e.id NOT IN (
SELECT manager_id
FROM employees
);Ada contributes a NULL manager ID. Use NOT EXISTS or the anti-join pattern instead.
Exercise
Why should an anti-join test report.id IS NULL instead of report.manager_id IS NULL?
Show answer
The primary key is non-NULL for every real matching report, so a NULL ID proves that no right-side row matched.