4 min read
•Question 17 of 29easyWhat are UNION, INTERSECT, and EXCEPT?
Combining result sets.
What You'll Learn
- UNION and UNION ALL
- INTERSECT
- EXCEPT (MINUS)
UNION
Combines results from two queries, removing duplicates.
query.sqlSQL
-- All customers and suppliers
SELECT name, city FROM customers
UNION
SELECT name, city FROM suppliers;
-- UNION ALL keeps duplicates (faster)
SELECT name FROM customers
UNION ALL
SELECT name FROM suppliers;Requirements
- Same number of columns
- Compatible data types
- Column names from first query
INTERSECT
Returns only rows that appear in both results.
query.sqlSQL
-- Cities with both customers and suppliers
SELECT city FROM customers
INTERSECT
SELECT city FROM suppliers;EXCEPT (MINUS in Oracle)
Returns rows from first query not in second.
query.sqlSQL
-- Customers not in suppliers
SELECT name FROM customers
EXCEPT
SELECT name FROM suppliers;
-- Products never ordered
SELECT id FROM products
EXCEPT
SELECT DISTINCT product_id FROM order_items;Practical Example
query.sqlSQL
-- Combine multiple status queries
SELECT id, name, 'VIP' as customer_type
FROM customers WHERE total_purchases > 10000
UNION ALL
SELECT id, name, 'Regular'
FROM customers WHERE total_purchases BETWEEN 1000 AND 10000
UNION ALL
SELECT id, name, 'New'
FROM customers WHERE total_purchases < 1000
ORDER BY customer_type, name;Comparison
| Operator | Duplicates | Use Case |
|---|---|---|
| UNION | Removed | Combine unique |
| UNION ALL | Kept | Combine all |
| INTERSECT | Removed | Common rows |
| EXCEPT | Removed | Difference |