Lesson 23: UNION, INTERSECT & EXCEPT
24 Jul 2026 1 min Swarnil Singhai
Set operators combine the results of two queries — UNION merges, INTERSECT keeps only rows in both, EXCEPT keeps only rows in the first but not the second.
Real-time example
Build a mailing list combining active customers and newsletter-only subscribers, without duplicates.
SELECT email FROM customers WHERE active = true
UNION
SELECT email FROM newsletter_subscribers;
-- customers who bought but never subscribed to the newsletter:
SELECT email FROM customers
EXCEPT
SELECT email FROM newsletter_subscribers;
What's happening
UNION removes duplicate rows by default; UNION ALL keeps duplicates and is faster since it skips the dedup step.
Both queries in a set operation must return the same number of columns with compatible types.
Advertisement