BBampaa

Lessons › SQL › Deep Dive: Advanced Joins & Subqueries

SQL lesson

INTERSECT and EXCEPT

INTERSECT returns only the rows that appear in both result sets, while EXCEPT returns rows from the first set that have no match in the second.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Comparing Retail Customer Sets with INTERSECT and EXCEPT

SELECT customer_id FROM orders
INTERSECT
SELECT customer_id FROM returns;

SELECT customer_id FROM orders
EXCEPT
SELECT customer_id FROM returns

Result:

analysiscustomer_id
ordered_and_returnedC002
ordered_and_returnedC003
ordered_but_no_returnC001
ordered_but_no_returnC004
ordered_but_no_returnC005

Step by step

  1. After SELECT, list the column names you want, separated by commas.
    SELECT customer_id
  2. FROM tells SQL which table to pull the data from.
    SELECT customer_id
    FROM orders
  3. INTERSECT keeps only rows that appear in both result sets.
    SELECT customer_id
    FROM orders
    INTERSECT

Practice

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

1. Write a query that returns rows in customers but NOT in reviews, using customers and reviews.
SELECT * FROM customers EXCEPT SELECT * FROM reviews

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