UNION & UNION ALL
Stack two query results into one — with or without deduplication
Merging Result Sets
UNION combines results from two SELECT statements into a single unified result set. Both queries must produce the same number of columns with compatible data types. Here's the difference between the two variants:
How UNION Works
Stack two result sets vertically
- UNION combines + deduplicates rows from two queries
- UNION ALL keeps all rows — no dedup (faster)
- Both queries must have same column count + compatible types
- Column names come from the FIRST SELECT
UNION vs UNION ALL
Dedup or not?
UNION Rules
Column matching requirements
- Same number of columns in both SELECTs
- Compatible data types (number/number, text/text)
- ORDER BY applies to the FINAL combined result
- Column names always from the first query
UNION Gotchas
Watch out for these
- UNION is slow on large sets — always prefer UNION ALL if possible
- Column type mismatch → implicit casting or error
- ORDER BY in individual SELECTs is ignored (use final ORDER BY)
- Mixing NULLs: NULL = NULL for dedup purposes in UNION
UNIONCombine + remove duplicates (slower)UNION ALLCombine + keep all rows (faster)| name | country |
|---|---|
| Aarav Sharma | India |
| Sara Chen | Singapore |
| James Wilson | UK |
| Maria Garcia | Spain |
| Yuki Tanaka | Japan |
| Priya Patel | India |
| Alex Johnson | USA |
| Chen Wei | China |
| Emma Brown | Australia |
| Omar Hassan | UAE |
| Lena Muller | Germany |
| Ravi Kumar | India |
| name | category |
|---|---|
| Wireless Mouse | Electronics |
| Office Desk | Furniture |
| LED Desk Lamp | Furniture |
| USB-C Cable | Electronics |
| Bluetooth Speaker | Electronics |
| Office Chair | Furniture |
| Coffee Maker | Appliances |
| Notebook Set | Stationery |
| Wireless Headphones | Electronics |
| Standing Desk | Furniture |
Worked Example
Create a combined list of all unique countries and cities from the customers table.
| location | type |
|---|---|
| Australia | Country |
| Bangalore | City |
| Berlin | City |
| China | Country |
| Delhi | City |
Key Concepts
Pro Tip
UNION is how you merge data from different queries, time periods, or sources into a unified result.
When to Use
Combining current and archived data, merging results from different conditions, creating unified reports from separate queries.
Create a combined list showing customer names labeled 'Customer' and product names labeled 'Product'. Use UNION ALL. Name columns: name, type.