Sub topic 4
UNION ALL: keeping every row
This chapter assumes you can write SELECT queries with WHERE, you know what DISTINCT does, and you have read the previous chapters on union compatibility and UNION. Here you will see what UNION ALL does differently, why that makes it the better default for many queries, and which mistakes it invites.
What UNION ALL does
UNION ALL appends the rows of the second query to the rows of the first. It does not compare rows, remove duplicates, or sort anything. If a query returns 3 rows and the other returns 2, the combined result has exactly 5 rows.
UNION does the same append and then removes duplicate rows from the combined result. UNION ALL skips that second step. All the compatibility rules still apply: both queries need the same number of columns, and the column types must be compatible by position.
The examples below use these tables. The multi-row VALUES syntax works in PostgreSQL, MySQL, SQL Server, and SQLite. Oracle needs one INSERT per row.
CREATE TABLE customers (
id INTEGER,
email VARCHAR(100),
phone VARCHAR(20)
);
CREATE TABLE newsletter_subscribers (
id INTEGER,
email VARCHAR(100)
);
INSERT INTO customers (id, email, phone) VALUES
(1, '[email protected]', '555-0101'),
(2, '[email protected]', '555-0102'),
(3, '[email protected]', NULL);
INSERT INTO newsletter_subscribers (id, email) VALUES
(1, '[email protected]'),
(2, '[email protected]');Note that [email protected] appears twice in customers and once in newsletter_subscribers.
Seeing every row
This query combines the two email lists and labels each row with its origin:
SELECT email, 'customer' AS source FROM customers
UNION ALL
SELECT email, 'subscriber' AS source FROM newsletter_subscribers;It returns five rows:
| source | |
|---|---|
| [email protected] | customer |
| [email protected] | customer |
| [email protected] | customer |
| [email protected] | subscriber |
| [email protected] | subscriber |
The two customer rows for Ben are identical. UNION ALL keeps both, because it never asks whether two rows are the same. The row order shown here is typical but not guaranteed. Without ORDER BY, the database may return the rows in any order.
The same email-only query with UNION returns three rows (ana, ben, cy), because UNION collapses all three Ben rows into one.
Why the literal source column matters
The source column in the example is a literal: a constant value written directly in the SELECT list. Literals are the usual way to record which branch a row came from. They also make the rows distinct. Two rows that differ only in source are no longer duplicates, so even a plain UNION would keep them. Because the literal is constant per branch, UNION ALL is the honest choice. The branches can never overlap, so a deduplication step could not remove anything and would only add work.
When UNION ALL is the right choice
Choose UNION ALL when any of the following is true:
- The branches cannot overlap. Rows from
orders_2025andorders_2026are different orders by construction. The same holds for rows filtered by non-overlappingWHEREconditions, such asstatus = 'open'andstatus = 'closed'. - Duplicates are meaningful. If two identical rows represent two real events, such as two sales of the same item for the same price on the same day, then
UNIONwould silently erase one of them. Your totals would then be wrong with no error to warn you. - You will aggregate afterwards. Counting or summing over the combined rows needs every row present.
- You do not need deduplication, and the data is large. The cost argument is covered below.
Choose UNION only when you actually want distinct rows in the output. If you are unsure whether the branches overlap, find out. Reaching for UNION "just in case" hides the question and costs performance.
Aggregating over a UNION ALL
A common pattern wraps the combined result in a derived table (a subquery in the FROM clause) and aggregates over it:
SELECT source, COUNT(*) AS row_count
FROM (
SELECT email, 'customer' AS source FROM customers
UNION ALL
SELECT email, 'subscriber' AS source FROM newsletter_subscribers
) AS combined
GROUP BY source;With the sample data this returns customer with 3 and subscriber with 2. If you replaced UNION ALL with UNION, the customer count would drop to 2, because the duplicate Ben row inside customers would be removed. This shows an important detail: UNION removes duplicates within a single branch as well as across branches. UNION ALL removes none.
Oracle does not allow AS before a table alias. In Oracle, write ) combined instead.
Filling in missing columns
UNION ALL requires the same number of columns on each side. When one source lacks a column, supply a placeholder. NULL is the usual choice, but give it an explicit type so that every database can resolve the column's type:
SELECT email, phone FROM customers
UNION ALL
SELECT email, CAST(NULL AS VARCHAR(20)) FROM newsletter_subscribers;Without the CAST, some databases (PostgreSQL in some contexts, SQL Server, and others) may infer an unexpected type or raise an error. The result here has five rows. The two subscriber rows have NULL in phone.
The reverse problem is a type mismatch. Combining a text column with a numeric column by position can fail or force an implicit conversion, which differs by database. Convert explicitly with CAST so the result does not depend on the dialect.
Column names and types come from the first query
The result's column names come from the first SELECT. Aliases in later branches are ignored. If the first branch has email and the second has contact_email, the output column is email.
Column types are resolved across all branches, and the rules vary. A common trap is a first-branch literal such as 'customer', which some databases type as a fixed-width character column. If a later branch supplies a longer string, you may see truncation or an error. When branches carry literals of different lengths, cast them to a common type, for example CAST('customer' AS VARCHAR(20)).
UNION ALL as the basis of partitioned views
Before native table partitioning, a common design stored one table per period and exposed them through a view:
CREATE VIEW orders_all AS
SELECT order_id, customer_id, total FROM orders_2025
UNION ALL
SELECT order_id, customer_id, total FROM orders_2026;Queries against orders_all read both tables. This works only because the view uses UNION ALL. Using UNION would force the database to deduplicate millions of rows on every query. Some optimizers can also skip a branch entirely when a filter on the view contradicts a CHECK constraint on the underlying table. That optimization is database-specific, so check your system's documentation before relying on it.
Mixing UNION and UNION ALL
You can chain several set operators in one statement. Without parentheses, UNION and UNION ALL are applied from left to right. A UNION in the chain deduplicates everything accumulated so far, including rows that came from earlier UNION ALL steps. A UNION ALL after it then appends rows without deduplicating them. Because the result depends on position, add parentheses when you mix the two. A later chapter covers precedence and parentheses in detail.
Cost: why UNION ALL is cheaper
To remove duplicates, the database must compare rows. It usually does this by sorting the combined result or by building a hash table of every row seen so far. Either way, it needs memory, may spill to disk when the result is large, and cannot return the first row until it has seen enough input to decide. UNION ALL is a simple append and can stream rows as they arrive.
The saving grows with the result size. For a few hundred rows the difference is invisible. For millions of rows it can be the difference between a query that streams immediately and one that spends a long time in a sort. Check the plan with your database's EXPLAIN command. A UNION plan typically shows an extra sort, hash aggregate, or unique step that a UNION ALL plan lacks.
Common mistakes
- Using
UNION ALLand expecting distinct rows. Counts come out too high. If you need distinct rows, useUNION, or writeSELECT DISTINCTaround the combined result. - Using
UNIONand expecting every row. Totals come out too low, and nothing raises an error. - Relying on row order.
UNION ALLoften returns branch 1 followed by branch 2, but no standard guarantees it. AddORDER BYafter the last query when order matters. - Mismatched column order. Columns are matched by position, not by name. Swapping
email, phoneforphone, emailin one branch does not raise an error if the types are compatible. It silently puts phone numbers in the email column. - Forgetting the source label. When the output feeds a report, include a literal source column. Otherwise you cannot tell where a row came from.
Exercise
Using the sample tables, what does SELECT COUNT(*) FROM (SELECT email FROM customers UNION ALL SELECT email FROM newsletter_subscribers) AS t return, and what does the same query return with UNION instead? Explain the difference.
Show answer
The UNION ALL version returns 5, because it keeps all 3 customer rows and all 2 subscriber rows. The UNION version returns 3 ([email protected], [email protected], [email protected]), because it removes duplicate rows. This includes the duplicate Ben row inside customers and the Ben row that appears in both tables.
Exercise
A reporting query combines orders_2025 and orders_2026 with UNION. Both tables hold millions of rows, and an order can never appear in both. Which operator should you use, and why? Name one risk of the operator you are replacing.
Show answer
Use UNION ALL. The tables cannot overlap, so deduplication removes nothing and only adds a sort or hash step over millions of rows. The risk with UNION is cost: extra memory, possible disk spills, and slower first-row response. It also carries a correctness risk, because two genuinely identical order rows (same ID-less values) within one table would be collapsed into one.
Exercise
You need to combine customers(email, phone) with newsletter_subscribers(email) and keep all rows. Write the query so that subscribers show NULL for phone and every row carries a source label.
Show answer
SELECT email, phone, 'customer' AS source FROM customers UNION ALL SELECT email, CAST(NULL AS VARCHAR(20)), 'subscriber' FROM newsletter_subscribers;