Sub topic 6
Finding Rows with No Match
This chapter assumes you know SELECT, FROM, WHERE, primary keys, foreign keys, NULL, and INNER JOIN ... ON. The examples use these tables:
customers(customer_id, name)orders(order_id, customer_id, total)
Customer Cleo has no orders. Order 104 has a NULL customer ID, so it belongs to no customer.
The anti-join pattern
An inner join returns only rows that match on both sides. To find customers without orders, start with every customer using a LEFT JOIN. An unmatched customer receives NULL values for the columns from orders.
SELECT c.name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id;The result includes rows such as:
| name | order_id |
|---|---|
| Ada | 101 |
| Ada | 102 |
| Ben | 103 |
| Cleo | NULL |
The NULL in order_id tells you that no order matched Cleo. Filter for that marker:
SELECT c.customer_id, c.name
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;This is called a left anti-join. It returns rows from the left table for which no matching row exists in the right table.
Use IS NULL, not = NULL. SQL uses three-valued logic, so comparisons with NULL do not produce TRUE.
`NOT EXISTS` states the intent directly
A correlated subquery checks whether an order exists for each customer. NOT EXISTS keeps the customer when the subquery finds no row.
SELECT c.customer_id, c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.customer_id
);The inner query is evaluated for the current customer. For Cleo, it finds no order, so NOT EXISTS is true.
LEFT JOIN ... IS NULL is useful when you also need columns from the joined table or want to show the join structure. NOT EXISTS often communicates the requirement more clearly: return customers for whom no related order exists. Query optimizers commonly produce similar execution plans, but you should still inspect performance for large data sets.
Why `NOT IN` can surprise you
This version looks similar:
SELECT c.name
FROM customers AS c
WHERE c.customer_id NOT IN (
SELECT o.customer_id
FROM orders AS o
);It can fail when the subquery returns NULL. Because order 104 has a NULL customer ID, the NOT IN comparison may become unknown for every customer, producing no rows. If you use NOT IN, exclude nulls explicitly:
SELECT c.name
FROM customers AS c
WHERE c.customer_id NOT IN (
SELECT o.customer_id
FROM orders AS o
WHERE o.customer_id IS NOT NULL
);For anti-join logic, prefer NOT EXISTS when the subquery column might contain NULL.
Exercise
Write a query that returns the IDs and names of customers with no orders, using a LEFT JOIN.
Show answer
SELECT c.customerid, c.name FROM customers AS c LEFT JOIN orders AS o ON o.customerid = c.customerid WHERE o.orderid IS NULL;