Medium Subqueries and CTEs Shop database

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

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

Expected result

name
Ravi Kumar
Kenji Sato

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

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.

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