Customers who never ordered
Task
Return the name of every customer with no orders. One order was imported without a customer, so orders.customer_id contains a NULL.
Row order does not matter. Column names do not have to match. SQLite dialect.
Tables
customers
id INTEGER, name TEXT
| id | name |
|---|---|
| 1 | Asha |
| 2 | Ben |
| 3 | Chen |
| 4 | Dev |
orders
id INTEGER, customer_id INTEGER, amount INTEGER
| id | customer_id | amount |
|---|---|---|
| 10 | 1 | 300 |
| 11 | 1 | 150 |
| 12 | 3 | 80 |
| 13 | NULL | 60 |
- Try NOT IN first and look at the result: why is it empty?
- Use NOT EXISTS, or a LEFT JOIN that keeps rows where the order side IS NULL.
Expected output
| name |
|---|
| Ben |
| Dev |
Show solution
SQL
SELECT c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);With a NULL in the list, id NOT IN (1, 3, NULL) is never TRUE, so NOT IN returns no rows. NOT EXISTS and LEFT JOIN … IS NULL are both NULL-safe.
Why this works
With a NULL in the list, id NOT IN (1, 3, NULL) is never TRUE, so NOT IN returns no rows. NOT EXISTS and LEFT JOIN … IS NULL are both NULL-safe.
The full explanation, with more examples, is in the question Customers who never ordered.