Set operations help combine or compare data from two or more tables easily. They let you find common, different, or all data without writing complex code.
Why set operations are needed in SQL
SELECT column_list FROM table1 UNION | UNION ALL | INTERSECT | EXCEPT SELECT column_list FROM table2;
All SELECT statements must have the same number of columns and compatible data types.
UNION removes duplicates, UNION ALL keeps all rows, INTERSECT finds common rows, EXCEPT finds rows in first but not in second.
SELECT name FROM customers_in_storeA UNION SELECT name FROM customers_in_storeB;
SELECT product_id FROM online_products INTERSECT SELECT product_id FROM physical_store_products;
SELECT employee_id FROM departmentX EXCEPT SELECT employee_id FROM departmentY;
This example creates two tables with customer names from two stores. The UNION query lists all unique customers who bought from either store.
CREATE TABLE storeA_customers (name VARCHAR(20)); CREATE TABLE storeB_customers (name VARCHAR(20)); INSERT INTO storeA_customers VALUES ('Alice'), ('Bob'), ('Charlie'); INSERT INTO storeB_customers VALUES ('Bob'), ('Diana'); SELECT name FROM storeA_customers UNION SELECT name FROM storeB_customers;
Set operations work best when columns match in number and type.
UNION removes duplicates, so it can be slower than UNION ALL.
Not all databases support INTERSECT and EXCEPT; check your system.
Set operations combine or compare data from multiple tables simply.
They help find common, different, or all unique rows.
Use UNION, INTERSECT, and EXCEPT to answer real-world questions about data overlap and difference.