SQL UNION vs UNION ALL: Duplicates, Totals and Ordering
Choose UNION or UNION ALL using row identity, source labels, NULLs and final ORDER BY. Includes executed SQL and a 615-check in-memory SQLite lab.
UNION ALL preserves row occurrences; UNION removes duplicates across the full selected row. Choose based on the intended data grain, then specify final ordering explicitly. Adding a source label, omitting a key or combining different types can change which rows collapse.
Decide what a duplicate means before choosing the operator
UNION ALL preserves every row occurrence from its inputs. UNION removes duplicate result rows, including duplicates already present within one input. The comparison uses the selected row, not an implicit business key. If you select customer_id and amount, two rows with the same customer but different amounts remain different result rows.
This matters when combining daily extracts, event feeds or overlapping customer segments. If each row represents a separate transaction, identical displayed values may still be two valid events. If each row represents membership in a customer set, duplicate identifiers may be unwanted. Write down the intended result grain before changing the query simply because its output appears repetitive.
A union is also different from a join. A join combines matching rows across columns according to a relationship; a union combines compatible result rows. PostgreSQL’s documentation requires the inputs to have the same number of columns and compatible corresponding types. Select columns explicitly in the intended positions rather than relying on SELECT * across schemas that can evolve independently.
Keep source identifiers available while diagnosing an unexpected total. Count the input occurrences and inspect the exact selected columns. Two source rows that look identical in a report may differ in an omitted identifier; conversely, two different source records can become indistinguishable when the projection drops their identifiers. The operator cannot infer which business interpretation you meant.
Source: PostgreSQL — combining queries with set operations ↗
A seven-row example where removing duplicates changes the total
The fixture below uses two small tables. Table a has four occurrences, including a repeated (2, 10) row. Table b has three occurrences and overlaps a. These are synthetic records, not measured customer transactions. The NULL identifier is included to make duplicate handling visible without inventing a missing business identity.
Combining the selected id and amount with UNION ALL yields seven rows and a sum of 70. UNION yields four distinct rows and a sum of 45. Neither total is automatically the correct business answer. The first preserves every occurrence; the second counts each distinct selected pair once. Removing repeated records can be appropriate only if that pair defines the intended identity.
If instead you select only amount, UNION produces the three values 5, 10 and 20. That is a distinct set of amounts, not one row per customer or transaction. Summing it would answer a third question. Projection changes the duplicate definition, so review every selected column when a seemingly harmless refactor changes a count.
| Combination | Result occurrences | SUM(amount) |
|---|---|---|
| id, amount with UNION ALL | 7 | 70 |
| id, amount with UNION | 4 | 45 |
| amount only with UNION | 3 distinct amounts | 35 |
CREATE TABLE a(id INTEGER, amount INTEGER);
CREATE TABLE b(id INTEGER, amount INTEGER);
INSERT INTO a VALUES (1,10),(2,10),(2,10),(NULL,5);
INSERT INTO b VALUES (2,10),(3,20),(NULL,5);
SELECT id, amount FROM a
UNION ALL
SELECT id, amount FROM b;
SELECT id, amount FROM a
UNION
SELECT id, amount FROM b;Adding a source label changes which rows can collapse
A common debugging improvement is to include a source column. This is valuable for lineage, but it also changes the selected row. With source a or b included, an otherwise identical pair from different tables is no longer equal across all result columns. UNION therefore retains both source-labeled versions.
In this fixture, UNION over source, id and amount yields six rows. The repeated pair within table a still collapses because its source label is the same, while matching pairs from a and b stay separate. If you wanted a single reconciled record per customer, adding source did not implement that reconciliation; it preserved more evidence about the inputs.
For actual reconciliation, define a business key and a deterministic conflict policy: for example, which version is eligible and how ties are resolved. Preserve the original records until that policy is validated. UNION is not a latest-record operator, and it does not decide that one source is more authoritative than another.
SELECT 'a' AS source, id, amount FROM a
UNION
SELECT 'b', id, amount FROM b;Apply an explicit final order and know what LIMIT limits
Neither operator is a promise about presentation order. UNION ALL may appear to return the first branch followed by the second in a small test, while UNION may appear sorted because of an implementation detail. PostgreSQL and SQLite both document that output order without an appropriate ORDER BY must not be relied on. Treat an observed sequence as a plan outcome, not an interface contract.
Use a final ORDER BY for the combined result. Add tie-breaking columns that make the required order unambiguous for the application. If distinct events can share every displayed sort value, retain an event identifier or another suitable key when their relative position matters. A limit applied to unresolved ties cannot establish a stable subset of those events.
The query below orders the entire seven-row UNION ALL result and then takes two rows. In the fixture, those are (3, 20) and (1, 10). Its trailing LIMIT does not select two rows independently from each input. To limit a branch before combination, use a subquery or CTE with the required branch-local ordering, following the target engine’s syntax, and still specify the final output order.
NULL ordering defaults differ across engines. The example explicitly uses NULLS LAST so the treatment of missing identifiers is visible. For paging a larger result, design the ordering and continuation rule together; adding UNION ALL does not repair unstable pagination caused by incomplete sort keys.
SELECT id, amount FROM a
UNION ALL
SELECT id, amount FROM b
ORDER BY amount DESC, id NULLS LAST
LIMIT 2;Test NULLs, types and collations on the engine you run
Duplicate elimination is not the same operation as filtering with an equality predicate. In SQLite compound-query duplicate comparison, NULL values compare equal to other NULL values for this purpose. The fixture’s two (NULL, 5) rows therefore collapse under UNION even though a normal NULL equality predicate has different semantics.
Type and text comparison rules can also change which rows are considered duplicates. The SQLite-specific tests below keep integer 1 and text 1 as distinct values, while an explicit NOCASE collation collapses the ASCII strings A and a. BINARY collation keeps those two strings separate. These narrow checks do not establish full Unicode case matching or portable cross-engine type conversion rules.
Use explicit casts and a documented collation when the result contract needs them, then test representative values on the deployed engine. Include missing values, numeric text, accents and locale-sensitive strings when they occur in real data. Do not repair an unexpected count by applying arbitrary lowercasing or casts without considering whether distinct business values should remain distinct.
Be careful when mixing set operators. SQLite groups chained compound operations from left to right; PostgreSQL gives INTERSECT a higher precedence than UNION and EXCEPT. Keep mixed expressions explicitly structured and follow the engine grammar. A demonstration involving only UNION and UNION ALL should not be generalized to every mixed set expression.
Source: SQLite SELECT — compound statements, comparison and ordering ↗
Run the full SQLite lab and independent occurrence checks
The complete Python script below creates only an in-memory SQLite database. The fixed cases verify the displayed totals, projected amounts, source labels, explicit ordering, NULLs, storage types, collations and a mismatched column-count error. The script also checks a mixed UNION/UNION ALL chain to show that a later UNION ALL can introduce repeated occurrences again.
For 200 seeded generated cases, the inputs contain bounded integers and optional NULL identifiers. Python Counter provides an independent occurrence-count expectation for UNION ALL. A Python set and a separate length check verify the distinct result for UNION under these restricted input types. Result comparisons deliberately avoid relying on an unspecified row order.
The exact published script passed 615 checks with Python 3.12.14 and SQLite 3.53.1. It is a correctness fixture, not a performance benchmark. No PostgreSQL server was executed. The generated oracle does not cover arbitrary mixed SQL types, custom collations, floating-point edge cases, recursive queries or other engines; the separate fixed SQLite cases have the narrower meanings described above.
import sqlite3
import random
from collections import Counter
checks = 0
def equal(actual, expected):
global checks
assert actual == expected, (actual, expected)
checks += 1
with sqlite3.connect(':memory:') as db:
db.executescript('CREATE TABLE a(id INTEGER, amount INTEGER);'
'CREATE TABLE b(id INTEGER, amount INTEGER);')
a = [(1, 10), (2, 10), (2, 10), (None, 5)]
b = [(2, 10), (3, 20), (None, 5)]
def load(left, right):
db.execute('DELETE FROM a'); db.execute('DELETE FROM b')
db.executemany('INSERT INTO a VALUES (?,?)', left)
db.executemany('INSERT INTO b VALUES (?,?)', right)
def query(sql):
return db.execute(sql).fetchall()
load(a, b)
union = 'SELECT id, amount FROM a UNION SELECT id, amount FROM b'
all_rows = 'SELECT id, amount FROM a UNION ALL SELECT id, amount FROM b'
equal(Counter(query(all_rows)), Counter(a+b))
equal(set(query(union)), set(a+b))
equal(len(query(union)), 4)
equal(query('SELECT SUM(amount) FROM ('+all_rows+')'), [(70,)])
equal(query('SELECT SUM(amount) FROM ('+union+')'), [(45,)])
equal(query('SELECT amount FROM a UNION SELECT amount FROM b ORDER BY amount'),
[(5,), (10,), (20,)])
equal(query(union+' ORDER BY id NULLS LAST, amount'),
[(1, 10), (2, 10), (3, 20), (None, 5)])
equal(query(all_rows+' ORDER BY amount DESC, id NULLS LAST LIMIT 2'),
[(3, 20), (1, 10)])
lineage = "SELECT 'a' AS source,id,amount FROM a UNION SELECT 'b',id,amount FROM b"
equal(len(query(lineage)), 6)
equal(query('SELECT NULL UNION SELECT NULL'), [(None,)])
equal(len(query("SELECT 1 UNION SELECT '1'")), 2) # SQLite storage types
equal(len(query("SELECT 'A' COLLATE NOCASE UNION SELECT 'a'")), 1)
equal(len(query("SELECT 'A' COLLATE BINARY UNION SELECT 'a'")), 2)
equal(Counter(query('SELECT 1 UNION SELECT 2 UNION ALL SELECT 2')),
Counter([(1,), (2,), (2,)]))
try:
query('SELECT id FROM a UNION SELECT id, amount FROM b')
except sqlite3.OperationalError:
checks += 1
else:
raise AssertionError('column mismatch accepted')
rng = random.Random(61)
for _ in range(200):
left = [(rng.choice([None, 0, 1, 2]), rng.randint(-2, 2))
for _ in range(rng.randrange(9))]
right = [(rng.choice([None, 0, 1, 2]), rng.randint(-2, 2))
for _ in range(rng.randrange(9))]
load(left, right)
equal(Counter(query(all_rows)), Counter(left+right))
result = query(union)
equal(set(result), set(left+right))
equal(len(result), len(set(left+right)))
print(f'{checks} checks passed; 200 seeded cases; SQLite {sqlite3.sqlite_version}')Choose semantics first, then measure the actual query
Use UNION ALL when every occurrence should survive, such as combining disjoint partitions or preserving an event stream for later processing. Use UNION when the intended result is a distinct set of the selected rows. If removing overlap requires a business-key conflict policy, express and test that policy directly instead of expecting UNION to select a preferred record.
Duplicate elimination can require additional work, but the execution strategy and cost depend on the engine, plan and data. Do not replace UNION with UNION ALL solely because a general rule says it is faster. First establish whether the outputs are equivalent for the actual contract, then inspect the plan and measure with representative inputs.
Before release, compare input counts, output counts, important totals, missing-value behavior and final order. Keep examples that would fail if a future edit added a source label or removed a key column. A correct choice remains explainable in one sentence: either every occurrence matters, or each distinct selected row should appear once.
Your next steps
- UNION compares the full selected row, not an implicit business key.
- UNION ALL preserves duplicates within and across inputs.
- Source labels change row identity; neither operator chooses the latest record.
- Use explicit final ordering and test engine-specific NULL, type and collation behavior.
Sources & official resources
Linked resources checked on 2026-10-30. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →