Lessons › SQL › Chapter 5: Joins, subqueries and CTEs
SQL lesson
Anti-join with LEFT JOIN and IS NULL
An anti-join finds rows that have no match. It's a LEFT JOIN, then a filter that keeps only the rows where the match came back empty. The first table you write (customers) is the left table: the one you want to check. The second (orders) is the right table.
Try this lesson free →Example
Finding rows that don't match
SELECT *
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id
WHERE orders.order_id IS NULL| customer_id | full_name | order_id | customer_id | revenue |
|---|---|---|---|---|
| C103 | Carol White | NULL | NULL | NULL |
Step by step
- The table you want to check. It's written first, so it's the left table.
SELECT * FROM customers - Join orders on the column both tables have. A customer with no orders gets empty order columns.
SELECT * FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id - Keep only the rows where the order columns are empty: the customers who never ordered.
SELECT * FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id WHERE orders.order_id IS NULL;
Practice
1. Using customers and orders, show every column. Show only the customers with no orders.
SELECT * FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id WHERE orders.order_id IS NULL2. Using customers and orders, show customer_id and full_name. Show only the customers with no orders.
SELECT c.customer_id, c.full_name FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id WHERE o.order_id IS NULL3. Using orders and returns, show every column. Show only the orders that weren't returned.
SELECT * FROM orders LEFT JOIN returns ON orders.order_id = returns.order_id WHERE returns.order_id IS NULL4. Using products and reviews, show every column. Show only the products with no reviews.
SELECT * FROM products LEFT JOIN reviews ON products.product_id = reviews.product_id WHERE reviews.product_id IS NULL5. Using products and inventory, show every column. Show only the products with no inventory record.
SELECT * FROM products LEFT JOIN inventory ON products.product_id = inventory.product_id WHERE inventory.product_id IS NULLLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →