Lesson

MySQL UNION ALL

10 min reading
Free Course

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 ALL First: Choose UNION ALL whenever duplicates either cannot happen (for example, disjoint status tags or mutually exclusive date partitions) or must be preserved (such as financial ledger entries). Switch to UNION only when deduplication is strictly required.
  • Avoid Splitting OR Queries Unnecessarily, Except for Index Merges: Rewriting WHERE customer_id = 5 OR referrer_id = 5 as two indexed SELECT branches combined with UNION ALL (or UNION if 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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum