Joins · Problem 45 of 118

Customers Who Never Ordered

MediumJoinsShop data

Return customer_id, first_name and last_name of every customer who has never placed an order.

Hint 1

A LEFT JOIN keeps every customer, and fills the order columns with NULL when nothing matches.

Hint 2

Then keep only the rows where the order side is NULL.

Reference solution

SELECT c.customer_id, c.first_name, c.last_name
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;

An INNER JOIN drops rows without a match, so it can never show "the ones without". A LEFT JOIN keeps every row of the left table; where there is no match the right-hand columns are NULL. Filtering on that NULL (use a column that can never be NULL in a real match, like the primary key) leaves exactly the unmatched rows. This anti-join is one of the most useful patterns in SQL.

Another way. NOT EXISTS says the same thing directly. It is also safe when the compared column can contain NULL, unlike NOT IN.

SELECT c.customer_id, c.first_name, c.last_name
FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id);