Set Operations in SQL
Set operations in SQL are used to combine the results of two or more SELECT queries. The
queries must have the same number of columns and the same data types in corresponding
columns.
UNION
Combines results of two queries and removes duplicates.
👉 Example:
SELECT customer_id FROM orders_2024
UNION
SELECT customer_id FROM orders_2025;
✔ Returns unique customer IDs from both years.
UNION ALL
Combines results of two queries including duplicates.
👉 Example:
SELECT customer_id FROM orders_2024
UNION ALL
SELECT customer_id FROM orders_2025;
✔ Returns all customer IDs, even if repeated.
INTERSECT
Returns only common rows from both queries. (Not supported in MySQL)
👉 Example:
SELECT customer_id FROM orders_2024
INTERSECT
SELECT customer_id FROM orders_2025;
✔ Customers who placed orders in both 2024 and 2025.
EXCEPT / MINUS
Returns rows from the first query that are not present in the second query. (MySQL does
not support directly)
👉 Example:
SELECT customer_id FROM orders_2024
EXCEPT
SELECT customer_id FROM orders_2025;
✔ Customers who ordered in 2024 but not in 2025.
Summary Table
Set Operation Description Duplicate Handling MySQL Support
UNION Combines results of Removes duplicates Supported
two queries
UNION ALL Combines results of Keeps duplicates Supported
two queries
INTERSECT Returns common Removes duplicates Not Supported
rows
EXCEPT / MINUS Returns rows from Removes duplicates Not Supported
first query not in
second