Loading…
While IN finds matching rows, NOT IN finds rows that don't match — this is extremely useful for finding missing or excluded data.
SELECT name FROM products
WHERE id NOT IN (SELECT DISTINCT product_id FROM order_items);
This finds products that have never been ordered.
| Question | NOT IN Pattern |
|---|---|
| Unsold products | <code>WHERE id NOT IN (SELECT product_id FROM order_items)</code> |
| Customers without orders | <code>WHERE id NOT IN (SELECT customer_id FROM orders)</code> |
| Employees without reviews | <code>WHERE id NOT IN (SELECT employee_id FROM reviews)</code> |
If the subquery returns any NULL values, NOT IN returns no rows at all! Always filter NULLs:
-- Safe version:
WHERE id NOT IN (SELECT product_id FROM order_items WHERE product_id IS NOT NULL)
Find all products that have never been ordered. Show only the product name.
Downloading SQL engine… (one-time)
This runs entirely in your browser and is cached for next time.