How to Use UNION in SQL
Use UNION when you need to combine the results of multiple SELECT queries into one result set. This is perfect for merging similar tables, combining archived data, or building unified feeds.
What you’ll build or solve
You’ll learn how to use UNION in SQL to merge compatible query results. You’ll also know when to use UNION ALL instead.
Learn SQL on Mimo
When this approach works best
This approach is the right choice when multiple queries return the same logical shape.
Common real-world scenarios include:
- Active + archived users
- Regional sales tables
- Event logs from multiple systems
- CRM + billing contact feeds
- Legacy + migrated data
This is a bad idea when the data belongs in one normalized table and should be combined with JOIN.
Prerequisites
You only need:
- Two or more
SELECTqueries - Matching column count
- Compatible column data types
Step-by-step instructions
Step 1: Stack compatible SELECT queries
Each query must return the same number of columns in the same order.
SQL
SELECT email
FROM active_users
UNION
SELECT email
FROM archived_users;
This combines both result sets and removes duplicates.
Use UNION ALL to keep duplicates.
SQL
SELECT email
FROM crm_contacts
UNION ALL
SELECT email
FROM billing_contacts;
This is usually faster because it skips deduplication.
What to look for:
- Column counts must match
- Data types must be compatible
UNIONremoves duplicatesUNION ALLkeeps everything- Great for merged feeds
Examples you can copy
Current + archived orders
SQL
SELECT order_id
FROM orders
UNION
SELECT order_id
FROM archived_orders;
Multi-region revenue rows
SQL
SELECT total
FROM sales_usa
UNION ALL
SELECT total
FROM sales_uk;
Legacy + new users
SQL
SELECT email
FROM legacy_users
UNION
SELECT email
FROM new_users;
Common mistakes and how to fix them
Mistake 1: Mismatched column counts
What the reader might do:
SQL
SELECT email, name
UNION
SELECT email
Why it breaks: both queries must return the same number of columns.
Corrected approach:
Align the selected columns.
Mistake 2: Expecting duplicates to remain with UNION
What the reader might do:
SQL
UNION
Why it breaks: duplicates are removed automatically.
Corrected approach:
Use UNION ALL.
Mistake 3: Mixing incompatible data types
What the reader might do:
Combine INT IDs with text labels in the same column position.
Why it breaks: implicit casting may fail or produce poor results.
Corrected approach:
Align compatible data types.
Troubleshooting
If SQL errors, confirm the same column count.
If duplicates disappear, switch to UNION ALL.
If sorting is needed, add one final ORDER BY after the last query.
If the logic models relationships, consider JOIN instead.
Quick recap
- Use
UNIONto combine result sets - Queries must return the same shape
UNIONremoves duplicatesUNION ALLkeeps duplicates- Add one final
ORDER BYat the end
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot