SQL UNION operator
Here is a clear, practical guide to the SQL UNION operator, with examples, rules, and best-practice notes.
β
What UNION Does
UNION combines the result sets of two or more SELECT statements into a single result set.
-
Duplicates are removed (like
SELECT DISTINCT). -
Columns must be compatible (same number of columns and compatible data types).
πΉ Basic Syntax
πΉ Example: Combine data from two tables
β Removes duplicate rows
β Returns one combined result set
π₯ UNION ALL (keeps duplicates)
UNION ALL is faster because it does NOT check for duplicates.
Use when:
-
You want all rows, including duplicates
-
You want better performance on large datasets
π§ Important Rules
-
Each SELECT must have the same number of columns
-
Columns must be in the same order
-
Columns must be compatible types (e.g., INT with BIGINT, VARCHAR with TEXT)
-
ORDER BYapplies once at the end:
π₯ Practical Examples
1. Combine active and archived orders
2. Get a list of unique cities from multiple tables
3. Find all unique tags across two tag tables
π§ Using UNION inside subqueries
π Performance Tips
β Use UNION ALL when duplicates don’t matterβmuch faster
β Apply ORDER BY only at the end
β Ensure SELECTs are using indexed columns when possible
β Avoid mixing very different data types
