Skip to main content
03

Customers who never order

Easyanti-joinNOT EXISTSNULL

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

idname
1Noa
2Avi
3Dana
4Yossi

orders

idcustomer_idamount
13120.00
2180.50
3340.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

sql
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:

sql
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:

sql
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:

sql
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, add WHERE customer_id IS NOT NULL to the subquery.
  • An index on orders.customer_id lets the anti-join check each customer with an index lookup.

Reference solution

sql
SELECT c.name AS customer
FROM customers c
WHERE NOT EXISTS (
  SELECT 1
  FROM orders o
  WHERE o.customer_id = c.id
);