In Phase 10, we learned Joins β which combine tables horizontally (adding columns). In Phase 11, we learn Set Operations β which combine result sets vertically (adding rows).
Set Operations: Mathematical operations that take two or more SELECT result sets and combine them into a single result set based on set theory principles (Union, Intersection, and Difference).
Unlike a Join, which can connect any two tables, Set Operations require the result sets to be Compatible. If these three rules aren't met, MySQL will throw an error:
- Same Number of Columns: Both
SELECTstatements must return the exact same number of columns. - Compatible Data Types: The columns in the same position must have similar data types (e.g., you can't combine a
DATEcolumn with anINTcolumn). - Same Order: Even if names are different, the meaning of the data in each position should be the same for the result to make sense.
| Operator | Concept | MySQL Support |
|---|---|---|
| UNION | Combines rows and removes duplicates | β Native |
| UNION ALL | Combines rows, keeps duplicates | β Native |
| INTERSECT | Rows common to both sets | β Simulated (or 8.0.31+) |
| EXCEPT / MINUS | Rows in Set A but NOT in Set B | β Simulated (or 8.0.31+) |
Real-world data often lives in fragmented tables that are structurally identical but logically separate.
- Example: You have a
Current_Employeestable and anArchived_Employeestable. To get a list of "Everyone who has ever worked here," you need to stack these two tables vertically.
When you run a Set Operation:
- MySQL executes the first query and stores the result in a temporary memory buffer.
- It executes the second query.
- For UNION: It performs a Sort-and-Deduplicate pass to remove rows that appear in both sets.
- For UNION ALL: It simply appends the second result to the first β much faster!
SELECT col1, col2 FROM TableA
UNION
SELECT col1, col2 FROM TableB;The Master Contact List:
Combining a Customers table and a Suppliers table into one single mailing list.
SELECT Name, Email, 'Customer' AS Category FROM Customers
UNION
SELECT Name, Email, 'Supplier' AS Category FROM Suppliers;- Column Mismatch:
SELECT Name FROM T1 UNION SELECT Name, Age FROM T2will fail because the column counts don't match (1 vs 2). - Assuming Header Names come from the second query: In a Set Operation, the final column headers are always taken from the first query in the chain.
Sorting a Set Result:
If you want to sort the combined result, you only place the ORDER BY at the very end of the last query. It will apply to the entire unified result set.
SELECT Name FROM T1
UNION
SELECT Name FROM T2
ORDER BY Name ASC; -- Sorts the final combined list- Task 1: List the 3 strict rules a query must follow to be eligible for a
UNIONoperation. - Task 2: Write a query that combines
Productsfrom two different databases (e.g.,Electronics_DBandFurniture_DB) into a single list ofProduct_NameandPrice.