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.
SELECT statement must list the exact same number of columns.SELECT statement.SELECT col1, col2 FROM table_a
UNION
SELECT col1, col2 FROM table_b
ORDER BY col1 ASC;
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 | |
|---|---|---|
| [email protected] | Austin | active |
| [email protected] | Denver | archived |
UNION ALL When Duplicates Are Impossible: UNION forces 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 to UNION ALL to skip that extra work.ORDER BY / LIMIT Queries in Parentheses: A trailing ORDER BY sorts the entire UNION. If you need to take the top 3 from each branch before merging, wrap each branch: (SELECT ... LIMIT 3) UNION (SELECT ... LIMIT 3).SELECT statements have different column counts?MySQL rejects the query immediately with error 1222: The used SELECT statements have a different number of columns.
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.
UNION treat NULL values during deduplication?UNION treats identical rows containing NULL in the same positions as duplicates and keeps only one copy.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.