MySQL UNION ALL
MySQL UNION ALL: Fast Merging of Result Sets
The MySQL UNION ALL operator stacks the result sets of two or more SELECT queries together without removing duplicate rows. Because it skips the expensive sort or hash deduplication step, UNION ALL runs faster and uses less memory than UNION.
Basic Syntax
SELECT column1, column2 FROM table_a
UNION ALL
SELECT column1, column2 FROM table_b;
Just like UNION, every query branch must return the same number of columns, and the first branch defines the output column names.
Practical SQL Example
This query creates a combined ledger feed of recent orders from demo_orders and archived records from demo_archived_orders while keeping every transaction row:
SELECT id AS reference_id, customer_id, total_amount, 'current' AS source_table
FROM demo_orders
WHERE created_at >= '2026-01-01'
UNION ALL
SELECT id AS reference_id, customer_id, total_amount, 'archive' AS source_table
FROM demo_archived_orders
WHERE created_at >= '2026-01-01'
ORDER BY total_amount DESC
LIMIT 20;
| reference_id | customer_id | total_amount | source_table |
|---|---|---|---|
| 105 | 1 | 320.00 | current |
| 88 | 4 | 215.00 | archive |
Common Mistakes and Best Practices
- Default to
UNION ALLFirst: ChooseUNION ALLwhenever duplicates either cannot happen (for example, disjoint status tags or mutually exclusive date partitions) or must be preserved (such as financial ledger entries). Switch toUNIONonly when deduplication is strictly required. - Avoid Splitting
ORQueries Unnecessarily, Except for Index Merges: RewritingWHERE customer_id = 5 OR referrer_id = 5as two indexedSELECTbranches combined withUNION ALL(orUNIONif a row can match both) often beats a full table scan on multi-million-row tables.
Frequently Asked Questions
How much faster is UNION ALL than UNION?
On large result sets, UNION ALL streams rows immediately without buffering a temporary deduplication table, cutting execution time and disk I/O significantly.
Can I use LIMIT on individual branches inside UNION ALL?
Yes, wrap any branch that has its own ORDER BY or LIMIT in parentheses before combining them.
What if one branch returns an INT and the other returns a VARCHAR?
MySQL widens the column type (converting integers to strings) so both branches share one compatible output type.
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.