UNION, INTERSECT, and EXCEPT
SQL · 13 questions
Short notes
Key idea
Set operations stack the results of two queries on top of each other (instead of side by side like a join).
Syntax
SELECT city FROM customers
UNION -- combined, duplicates removed
SELECT city FROM stores;
UNION ALL -- combined, duplicates kept (faster)
INTERSECT -- in both
EXCEPT -- in the first but not the second
Both queries need the same number of columns, with matching types, in the same order.
Example
Customers who signed up but never ordered:
SELECT customer_id FROM customers
EXCEPT
SELECT customer_id FROM orders;
Traps
UNIONsilently removes duplicates. If you're adding up rows from two months, useUNION ALL.- Columns match by position, not name. Swapping two columns in one query mixes them up.
- Column names come from the first query.
- One
ORDER BYat the very end sorts the combined result.
Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →
- Question 1easy
What's the difference between
UNIONandUNION ALL? - Question 2medium
SELECT first_name, city FROM a UNION ALL SELECT city, first_name FROM b. What happens? - Question 3medium
Customers live in 9 cities, and some have no city. What does this return?
SELECT COUNT(*) FROM ( SELECT city FROM customers UNION SELECT city FROM customers );
- Question 4medium
What does this return?
SELECT COUNT(*) FROM ( SELECT customer_id FROM orders WHERE status = 'delivered' INTERSECT SELECT customer_id FROM orders WHERE status = 'cancelled' );
- Question 5hard
38 customers have visited the website while logged in, and all 31 customers who ordered are among them. What does this return?
SELECT COUNT(*) FROM ( SELECT customer_id FROM orders EXCEPT SELECT customer_id FROM web_sessions );
UNION, INTERSECT, and EXCEPT
UNION, INTERSECT, and EXCEPT
UNION, INTERSECT, and EXCEPT
UNION, INTERSECT, and EXCEPT
UNION, INTERSECT, and EXCEPT
8 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.