SQL: Select Rows in Table A Not in Table B
Find customers with no orders using LEFT JOIN … IS NULL, NOT EXISTS, or NOT IN — and which pattern to prefer.
What this question means
“Select data from table A that is not in table B” = an anti-join. On our shop: customers who never placed an order.
Pattern 1 — LEFT JOIN + IS NULL (most visual)
SELECT c.customer_id, c.first_name FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id WHERE o.order_id IS NULL;
Keep all customers, attach orders, then keep only rows where the join found nothing.
Pattern 2 — NOT EXISTS (often safest)
SELECT c.customer_id, c.first_name FROM customers c WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id );
Reads as English. Behaves well with NULLs compared to NOT IN.
NOT IN caution
NOT IN (SELECT customer_id FROM orders) can surprise you if the subquery returns a NULL. Prefer NOT EXISTS or the LEFT JOIN pattern when NULLs are possible.
FAQ
How do I get rows that exist in A but not in B?
Use LEFT JOIN from A to B and filter WHERE B.key IS NULL, or WHERE NOT EXISTS (SELECT 1 FROM B WHERE …).
Try it yourself
The fastest way to lock this in is a short drill on the same Northstar Market tables.