BeginnerJoins & NULLs

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

idname
1Asha
2Ben
3Chen
4Dev

orders

id INTEGER, customer_id INTEGER, amount INTEGER

idcustomer_idamount
101300
111150
12380
13NULL60
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.

The full explanation, with more examples, is in the question Customers who never ordered.