Hard SQL joins practice Shop database

Find rows with no match (anti-join)

Question

Show the name of customers who have never had an order with status 'shipped'.

customersid, name, country, joined_on
productsid, name, category, price
ordersid, customer_id, ordered_on, status
order_itemsorder_id, product_id, quantity

Your query

Ctrl+Enter to run

Result

Press Run to see your query's result, or Check answer to compare it with the expected result.

Expected result

name
Kenji Sato

Rows can come in any order. Column names do not have to match.

Hint

LEFT JOIN to the shipped orders only, then keep the rows where no order was found.

Show the solution
solution.sql Run this code
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'shipped'
WHERE o.id IS NULL;

Why it works

The status test is part of the ON clause, so the LEFT JOIN only looks for shipped orders. Customers with none get NULL in every order column, and WHERE o.id IS NULL keeps exactly them.

Common mistake

Putting o.status = 'shipped' in the WHERE clause instead of ON removes the NULL rows again and turns the LEFT JOIN back into an inner join, so the query returns nothing.

Want to try the query on MySQL or PostgreSQL? Open it in the SQL Online Compiler or SQLite Online.