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 →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| analysis | customer_id |
|---|---|
| ordered_and_returned | C002 |
| ordered_and_returned | C003 |
| ordered_but_no_return | C001 |
| ordered_but_no_return | C004 |
| ordered_but_no_return | C005 |
Step by step
- After SELECT, list the column names you want, separated by commas.
SELECT customer_id - FROM tells SQL which table to pull the data from.
SELECT customer_id FROM orders - INTERSECT keeps only rows that appear in both result sets.
SELECT customer_id FROM orders INTERSECT
Practice
1. Write a query that returns rows in customers but NOT in reviews, using customers and reviews.
SELECT * FROM customers EXCEPT SELECT * FROM reviewsLearn 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 →