BBampaa

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 →
About 5–10 minutes · no sign-up needed

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

Result:

customer_idfull_nameorder_idcustomer_idrevenue
C103Carol WhiteNULLNULLNULL

Step by step

  1. The table you want to check. It's written first, so it's the left table.
    SELECT *
    FROM customers
  2. 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
  3. 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

Try each one in your head first, then open the answer.

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 NULL
2. 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 NULL
3. 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 NULL
4. 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 NULL
5. 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 NULL

Learn 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 →
About 5–10 minutes · no sign-up needed