Sub topic 10
NULL Keys, Outer Joins, and Anti-Joins
This chapter assumes you know basic JOIN syntax, GROUP BY, and the three-valued logic from earlier chapters: a comparison with NULL yields UNKNOWN, and WHERE keeps only rows where the condition is TRUE. Here you will see how those rules shape join results. You will also learn how to write an anti-join, which finds rows that have no match.
All examples use the employees table from earlier in this tutorial:
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INTEGER,
commission NUMERIC(8,2)
);
INSERT INTO employees (id, name, manager_id, commission) VALUES
(1, 'Ada', NULL, NULL),
(2, 'Ben', 1, 100.00),
(3, 'Cy', 1, NULL),
(4, 'Di', 2, 300.00);NULL keys never match in a join
A join condition such as a.x = b.y is a comparison like any other. If either side is NULL, the result is UNKNOWN. An inner join keeps a pair of rows only when the ON condition is TRUE, so a row whose join key is NULL never matches anything. That includes another row whose key is also NULL.
Consider a self-join that pairs each employee with their manager:
SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON e.manager_id = m.id;The result has three rows:
| employee | manager |
|---|---|
| Ben | Ada |
| Cy | Ada |
| Di | Ben |
Ada is missing. Her manager_id is NULL, so e.manager_id = m.id is UNKNOWN for her row against every possible partner. She is dropped silently, and no error or warning appears.
Two NULL keys do not match each other either. NULL = NULL is UNKNOWN, not TRUE. If two tables both contain rows with a NULL in the join column, an inner join on that column will not pair them up.
Outer joins create NULLs
An outer join keeps rows that have no match and fills the columns of the missing side with NULL. To keep Ada in the result, use a LEFT JOIN:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;This returns four rows. Ada appears with manager set to NULL.
The NULL in the output now has two possible origins:
- The matched row existed, and its own column was NULL.
- No matching row existed, and the database filled in NULL.
The output looks the same in both cases. If you need to tell them apart, test a column that can never be NULL in a matched row, such as the right table's primary key or a NOT NULL column. For m, that is m.id.
Filtering outer joins: ON versus WHERE
A common mistake is putting a condition on the right-hand table in the WHERE clause of a LEFT JOIN. WHERE runs after the join. The NULL-filled rows have NULL in every right-side column, so a condition on those columns is UNKNOWN and the row is removed.
-- Intended: all employees, with their manager's name if the manager earns commission.
-- Actual: behaves like an INNER JOIN, so Ada, Cy, and Ben are lost.
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
WHERE m.commission > 0;Only Di survives. Her manager is Ben, and Ben's commission is 100. Ada's row has m.commission NULL from the fill. Ben's manager is Ada, whose commission is NULL. Cy's manager is also Ada.
Move the condition into ON to restrict which rows match, while still keeping every left row:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.id
AND m.commission > 0;This returns all four employees. Only Di gets a non-NULL manager (Ben), because only Ben has a positive commission. The others get NULL in manager.
The rule of thumb:
- A condition in ON decides which rows match. Unmatched left rows survive.
- A condition in WHERE decides which result rows survive. It runs after the NULL fill.
For inner joins the two placements give the same result. For outer joins they do not.
Anti-joins: finding rows with no match
An anti-join returns rows from one table that have no matching row in another. There are two reliable ways to write one in SQL.
LEFT JOIN with an IS NULL test
Join, then keep only the rows where the right side was filled with NULL:
-- Employees with no direct reports.
SELECT e.name
FROM employees e
LEFT JOIN employees m ON m.manager_id = e.id
WHERE m.id IS NULL;Here m.id is the primary key of m, so it is never NULL in a real match. A NULL there can only mean "no match". The query returns Cy and Di.
Testing a nullable column would be a bug. If you wrote WHERE m.commission IS NULL, you would also return employees whose matching report exists but has no commission.
NOT EXISTS
SELECT e.name
FROM employees e
WHERE NOT EXISTS (
SELECT 1 FROM employees m WHERE m.manager_id = e.id
);This returns the same two rows. EXISTS tests only whether the subquery returns any row. It never compares the subquery's output values to anything, so NULLs in the subquery have no effect on the outcome.
Why not NOT IN
The previous chapter showed that NOT IN returns no rows when the subquery produces a NULL. In this table, manager_id contains a NULL for Ada, so id NOT IN (SELECT manager_id FROM employees) is never TRUE. Anti-joins are the safe replacement.
Choosing between the two forms
| Form | Strength | Watch for |
|---|---|---|
| `LEFT JOIN ... WHERE right.pk IS NULL` | Familiar, easy to extend with extra joins | You must test a column that is never NULL in a real match |
| `NOT EXISTS` | States the intent directly; unaffected by NULLs in the subquery | Correlated subquery syntax is longer |
Most modern optimizers turn both forms into the same anti-join plan, so choose on clarity. Measure with your database's EXPLAIN if performance matters, because older versions and some systems plan them differently.
Matching NULL to NULL on purpose
Sometimes NULL means "no value" in both tables, and you want those rows to pair up. The standard operator for this is IS NOT DISTINCT FROM, which treats two NULLs as equal:
SELECT a.id, b.id
FROM table_a a
JOIN table_b b ON a.code IS NOT DISTINCT FROM b.code;Support varies. PostgreSQL, SQLite (3.39+), and recent versions of other systems accept it. MySQL uses the <=> operator for the same purpose. Where neither exists, you can spell out the logic:
ON a.code = b.code OR (a.code IS NULL AND b.code IS NULL)Be careful with this. A join condition containing OR often prevents the optimizer from using an index, and the query can become much slower on large tables. It also pairs every NULL row on one side with every NULL row on the other, which can multiply rows. Before using it, ask whether those rows should be related at all. Often they should not.
Aggregating over outer joins
Outer joins interact with COUNT. Suppose you want the number of direct reports per employee, including zero:
SELECT e.name, COUNT(m.id) AS reports
FROM employees e
LEFT JOIN employees m ON m.manager_id = e.id
GROUP BY e.id, e.name
ORDER BY e.id;The result:
| name | reports |
|---|---|
| Ada | 2 |
| Ben | 1 |
| Cy | 0 |
| Di | 0 |
COUNT(m.id) skips NULLs, so employees with no reports get 0. COUNT(*) would return 1 for Cy and Di, because the NULL-filled row still counts as a row. When counting over an outer join, count a right-side column that is never NULL in a real match.
Common errors
- Expecting an inner join on a nullable column to keep NULL rows. They are dropped.
- Expecting two NULL keys to match.
NULL = NULLis UNKNOWN. - Putting a right-table condition in WHERE after a LEFT JOIN, which turns it into an inner join.
- Testing a nullable column for NULL in an anti-join, which returns false positives.
- Using
COUNT(*)after an outer join and getting 1 for groups with no matches. - Using
NOT INwith a subquery on a nullable column.
Exercise
Using the employees table, write a query that lists every employee together with the name of their manager's manager (the "grandmanager"), showing NULL where there is none. Which join type do you need, and how many rows should the result have?
Show answer
SELECT e.name, g.name AS grandmanager FROM employees e LEFT JOIN employees m ON e.managerid = m.id LEFT JOIN employees g ON m.managerid = g.id ORDER BY e.id; You need two LEFT JOINs so employees without a manager or grandmanager are kept. The result has 4 rows: Ada is NULL (no manager), Ben is NULL (his manager Ada has no manager), Cy is NULL, and Di has grandmanager Ada.
Exercise
A colleague writes SELECT e.name FROM employees e LEFT JOIN employees m ON m.manager_id = e.id WHERE m.commission IS NULL; to find employees with no direct reports. Which names does it return, and why is it wrong?
Show answer
It returns Ada, Cy, and Di. Cy and Di have no reports, so the fill makes m.commission NULL. Ada has two reports, Ben and Cy, and Cy's commission is NULL, so the row (Ada, Cy) passes the test too. Ada is a false positive. The fix is to test a column that is never NULL in a real match, such as m.id IS NULL.