Customers who never order
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Write a query that returns the names of customers who have never placed an order, in a column named customer.
Some orders are guest checkouts, so orders.customer_id can be NULL. Rows can be returned in any order.
Example
customers
| id | name |
|---|---|
| 1 | Noa |
| 2 | Avi |
| 3 | Dana |
| 4 | Yossi |
orders
| id | customer_id | amount |
|---|---|---|
| 1 | 3 | 120.00 |
| 2 | 1 | 80.50 |
| 3 | 3 | 40.00 |
Result:
| customer |
|---|
| Avi |
| Yossi |
Watch out
NOT IN and NULL don't mix. Make sure your query still works when an order has no customer.
Schema
CREATE TABLE customers (
id INT PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE orders (
id INT PRIMARY KEY,
-- NULL for guest checkouts.
customer_id INT REFERENCES customers (id),
amount NUMERIC(10, 2) NOT NULL
);Approach
Keep each customer for whom no matching order exists:
SELECT c.name AS customer
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);The LEFT JOIN anti-join is equivalent and just as common:
SELECT c.name AS customer
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;Filter on a column that is never NULL in a real match, like the primary key o.id.
The NOT IN trap
This looks right, and returns nothing as soon as one order has a NULL customer:
SELECT name FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);id NOT IN (1, 3, NULL) means id <> 1 AND id <> 3 AND id <> NULL. Comparing with NULL gives UNKNOWN, not TRUE, so the whole condition is never true. NOT EXISTS doesn't have this problem, and Postgres plans it as an efficient anti-join.
Follow-ups
- If you must use
NOT IN, addWHERE customer_id IS NOT NULLto the subquery. - An index on
orders.customer_idlets the anti-join check each customer with an index lookup.
Reference solution
SELECT c.name AS customer
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);