Filter with IN and a subquery
Question
Show the name of customers who ordered a Monitor.
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
Expected result
| name |
|---|
| Ravi Kumar |
| Kenji Sato |
Hint
Find the ids of orders that contain the Monitor, then the customers of those orders.
Show the solution
solution.sql
Run this code
SELECT name
FROM customers
WHERE id IN (
SELECT o.customer_id
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN products p ON p.id = i.product_id
WHERE p.name = 'Monitor'
);
Why it works
The subquery returns a list of customer ids, and IN keeps the customers whose id is in that list. Unlike a join, IN never repeats a customer, even if they ordered several monitors.
Common mistake
Be careful with NOT IN and subqueries that can return NULL. If the list contains a NULL, NOT IN matches nothing. NOT EXISTS is the safer choice.