MySQL UNION Operator
MySQL UNION Operator: Merging Distinct Result Sets
The MySQL UNION operator combines the rows from two or more SELECT queries into one unified result set and automatically removes duplicate rows. Every SELECT inside a UNION must return the exact same number of columns with compatible data types.
Basic Syntax and Rules
- Each
SELECTstatement must list the exact same number of columns. - Columns at the same position should have compatible data types (string with string, number with number).
- Column names in the final output come from the first
SELECTstatement.
SELECT col1, col2 FROM table_a
UNION
SELECT col1, col2 FROM table_b
ORDER BY col1 ASC;
Practical SQL Example
This query combines active rows from demo_customers and past contacts from demo_archived_customers into one deduplicated mailing list:
SELECT email, city, 'active' AS account_state
FROM demo_customers
WHERE is_active = 1
UNION
SELECT email, city, 'archived' AS account_state
FROM demo_archived_customers
ORDER BY email ASC;
| city | account_state | |
|---|---|---|
| alice@example.com | Austin | active |
| bob@example.com | Denver | archived |
Common Mistakes and Best Practices
- Use
UNION ALLWhen Duplicates Are Impossible:UNIONforces MySQL to sort or hash every combined row to eliminate duplicates. When merging disjoint sets (like'active'vs.'archived'if emails cannot overlap, or when duplicates are desired), switch toUNION ALLto skip that extra work. - Wrap Individual
ORDER BY/LIMITQueries in Parentheses: A trailingORDER BYsorts the entireUNION. If you need to take the top 3 from each branch before merging, wrap each branch:(SELECT ... LIMIT 3) UNION (SELECT ... LIMIT 3).
Frequently Asked Questions
What happens if the two SELECT statements have different column counts?
MySQL rejects the query immediately with error 1222: The used SELECT statements have a different number of columns.
Does UNION sort results automatically?
No, although older MySQL versions sometimes produced sorted output as a side effect of duplicate removal, always add an explicit ORDER BY at the end.
How does UNION treat NULL values during deduplication?
UNION treats identical rows containing NULL in the same positions as duplicates and keeps only one copy.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.