Sub topic 6
Finding rows with no match
This chapter assumes you can write a basic SELECT ... WHERE query and an INNER JOIN ... ON. It also assumes you know that NULL means "no value" and that NULL = NULL is not true. The chapter builds on the LEFT JOIN and NULL padding from the previous chapters.
An outer join can answer the question "which rows have no partner?" That question is common: customers who never ordered, products never sold, employees with no manager. The pattern that answers it is called an anti-join.
The sample data
This is the same data used in the earlier chapters. Cleo has no orders, and order 104 has no customer.
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT REFERENCES customers (customer_id),
total DECIMAL(10, 2) NOT NULL
);
INSERT INTO customers (customer_id, name) VALUES
(1, 'Ada'), (2, 'Ben'), (3, 'Cleo');
INSERT INTO orders (order_id, customer_id, total) VALUES
(101, 1, 50.00),
(102, 1, 20.00),
(103, 2, 35.00),
(104, NULL, 15.00);The idea: keep everything, then keep only the padding
A LEFT JOIN returns every customer. When a customer has no matching order, the database fills the order columns with NULL. Those padded rows are exactly the customers with no match.
So the recipe has two steps:
- LEFT JOIN from the table you want to check (the preserved side) to the table where matches might be missing.
- Keep only the rows where a right-table column is
NULL.
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
-- CleoThe database first builds the full LEFT JOIN result, which has four rows:
| name | order_id | total |
|---|---|---|
| Ada | 101 | 50.00 |
| Ada | 102 | 20.00 |
| Ben | 103 | 35.00 |
| Cleo | NULL | NULL |
Then WHERE o.order_id IS NULL removes the first three rows. Only Cleo remains.
Which column should you test for NULL?
The IS NULL test only works if a NULL in that column can mean one thing: "this row was padding". Choose the column with that in mind.
| Column tested | Safe? | Reason |
|---|---|---|
| `o.order_id` (right table primary key) | Yes | A primary key is never `NULL` in a real row, so `NULL` can only come from padding. |
| `o.customer_id` (the join column) | Yes | On a matched row it equals `c.customer_id`, which is never `NULL`. |
| A nullable data column, such as an optional `shipped_at` | No | A real order with no ship date would look like padding. |
| `c.name` (left table column) | No | The left side is preserved, so this is never padding. The query returns nothing. |
The simplest habit is to test the right table's primary key. That is why the example above uses o.order_id.
Reversing the direction
The preserved side decides what you can find. To find orders with no customer, put orders on the left:
SELECT o.order_id, o.total
FROM orders o
LEFT JOIN customers c ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL;
-- 104 15.00Order 104 has customer_id = NULL. A comparison such as NULL = 1 is neither true nor false but unknown, so a NULL foreign key never matches anything in the ON condition. The row is kept because orders is the preserved side, and it comes back padded.
You could write the same query as a RIGHT JOIN from customers to orders. Most people put the table they are checking on the left and use LEFT JOIN, as the earlier chapter on RIGHT JOIN recommended.
The two directions answer different questions:
- Customers with no orders: preserve
customers, test anorderscolumn. - Orders with no customer: preserve
orders, test acustomerscolumn.
In a well-designed schema the second query often returns nothing, because a foreign key constraint should prevent orphaned orders. Here it returns row 104 only because the foreign key column is nullable. A NULL foreign key is allowed even when the constraint is enforced. This anti-join is a standard data-quality check, and it is useful on legacy data or in tables without constraints.
Anti-join with extra conditions
Suppose you want customers with no order over 40. Ada has order 101 for 50.00, so she is excluded. Ben's only order is 35.00, so he qualifies, and so does Cleo.
The extra condition belongs in the ON clause:
SELECT c.name
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id
AND o.total > 40
WHERE o.order_id IS NULL;
-- Ben
-- CleoIn the ON clause, o.total > 40 decides which orders count as a match. Ben has an order, but it does not satisfy the condition, so Ben gets a padded row. The WHERE clause then keeps the padded rows.
If you move the condition into WHERE, the query breaks:
-- Wrong: returns no rows
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL
AND o.total > 40;A padded row has o.total = NULL, and NULL > 40 is unknown, so the row is discarded. The WHERE clause demands both "no order" and "an order over 40", which no row can satisfy. The next chapter covers ON versus WHERE in full. For anti-joins, the rule is that conditions describing the match go in ON, and only the IS NULL test goes in WHERE.
Counting unmatched rows
Because the anti-join returns ordinary rows, you can count them like any other result:
SELECT COUNT(*) AS customers_without_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
-- 1Here COUNT(*) is correct. After the WHERE filter, each remaining row is one unmatched customer, and each customer appears once, because a customer with no orders has exactly one padded row.
The same question with NOT EXISTS
SQL has another way to express "no matching row", and it returns the same customers:
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
-- CleoBoth forms are correct. The trade-offs:
- Intent.
NOT EXISTSstates the question directly: customers for whom no order exists. The LEFT JOIN form states a mechanism: join, then keep the padding. - Safety.
NOT EXISTShas no column to choose, so you cannot test the wrong column. - Extending the query. If you also want to show columns from the matched side, you need the join, and an anti-join shows none by definition.
- Performance. Many query planners turn both forms into the same anti-join plan, but this depends on the database and version. If the speed matters, compare the plans with
EXPLAINon your own data.
The last chapter returns to NOT EXISTS. It also covers NOT IN, which has a trap with NULL values. Order 104 has a NULL customer ID, so a query like WHERE customer_id NOT IN (SELECT customer_id FROM orders) would return no rows at all. Until then, prefer NOT EXISTS or the LEFT JOIN form.
Common mistakes
- Testing a left-table column.
WHERE c.name IS NULLnever finds unmatched customers. Test the right table. - Putting the match condition in WHERE. As shown above, this discards the padded rows you are trying to find.
- Using the wrong preserved side. If your result is empty when you expect rows, check which table is on the left.
- Using an inner join. An INNER JOIN has no padded rows, so there is nothing to test with
IS NULL. - Forgetting duplicate-free results. An anti-join returns each unmatched left row once. If you see repeated rows, you are likely selecting from a different join than you intended.
Practice
Exercise
Write a query that returns the names of customers who have no order with a total of 30 or more. Using the sample data, what does it return?
Show answer
Put the condition in ON and the IS NULL test in WHERE: SELECT c.name FROM customers c LEFT JOIN orders o ON o.customerid = c.customerid AND o.total >= 30 WHERE o.order_id IS NULL; Ada has order 101 (50.00) and Ben has order 103 (35.00), so both have a qualifying order and are excluded. Cleo has no orders, so she is the only result: Cleo.
Exercise
A colleague writes SELECT o.order_id FROM orders o LEFT JOIN customers c ON c.customer_id = o.customer_id WHERE c.name IS NULL; to find orders with no customer. It returns order 104 on the sample data. Is the query reliable?
Show answer
Not fully. It works here because c.name is declared NOT NULL, so the only way it can be NULL is through padding. But the safer choice is the customers primary key, c.customer_id IS NULL, which is NULL only for padding in any schema. If the name column were ever made nullable, a real customer with no name would be treated as missing. Also, the pattern depends on the preserved side being orders; it correctly finds orders without a customer.