Choose UNION or UNION ALL without losing meaningful rows

UNION ALL preserves the rows contributed by both queries, including repeats. UNION removes duplicate result rows. Choose between them according to what one row represents, because removing duplicates can discard valid events just as easily as it removes unwanted repetition.

These operations stack compatible rows. They do not join related columns from separate tables. The column count and position must line up, and each engine must be able to reconcile the corresponding data types.

Observe duplicates across and within inputs

Run this read-only query. The left input contains two BOLT rows, while the right input adds another. The output keeps all three.

SQL
WITH LeftCodes(Code) AS (
    SELECT 'BOLT' UNION ALL SELECT 'BOLT' UNION ALL SELECT 'NUT'
), RightCodes(Code) AS (
    SELECT 'BOLT' UNION ALL SELECT 'SEAL'
)
SELECT Code FROM LeftCodes
UNION ALL
SELECT Code FROM RightCodes
ORDER BY Code;

Expected output:

Plain text
BOLT
BOLT
BOLT
NUT
SEAL

Now run the complete distinct alternative.

SQL
WITH LeftCodes(Code) AS (
    SELECT 'BOLT' UNION ALL SELECT 'BOLT' UNION ALL SELECT 'NUT'
), RightCodes(Code) AS (
    SELECT 'BOLT' UNION ALL SELECT 'SEAL'
)
SELECT Code FROM LeftCodes
UNION
SELECT Code FROM RightCodes
ORDER BY Code;

This returns BOLT, NUT and SEAL once each. Duplicate elimination applies to the combined result, so it removes repetitions within one input as well as matches between the two inputs. It does not merely reject rows that appeared in both.

Remember that equality covers the whole row

Adding a source column changes the identity of a result row.

SQL
SELECT 'BOLT' AS Code, 'A' AS SourceName
UNION
SELECT 'BOLT', 'B'
ORDER BY SourceName;

Both rows remain because their SourceName values differ. If the goal is one row per Code, adding UNION to a projection that includes differing metadata will not enforce that goal. Define an explicit per-code selection or aggregation rule instead.

Similarly, two sales of the same amount are still two sales when their event identities differ. A report that unions only amounts can silently lose one of them. Include the required identity or preserve all events and aggregate afterward.

Order the final result explicitly

The examples place a single ORDER BY after the combined query. Without it, neither operator promises a display order. UNION ALL does not guarantee that every left-hand row appears before every right-hand row, and a distinct result is not promised to be sorted merely because one execution used a sort internally.

Branch-specific limiting and ordering require the engine's appropriate subquery or parenthesis syntax. A final limit ordinarily applies to the combined result. Keep that scope visible when adapting a query that takes the newest rows from several sources.

Check comparisons and cost separately

Distinctness follows the engine's type and collation rules. Text comparisons may ignore case, and duplicate elimination can treat NULLs as equivalent even though a predicate such as NULL = NULL is not true. Test the actual result types rather than assuming string representations establish equality.

UNION must perform duplicate elimination, while UNION ALL does not request that work. The exact plan may use sorting, hashing or another strategy. Select the correct semantics first, then inspect the plan on realistic data. Replacing UNION with UNION ALL is valid only when repeated rows are allowed or the inputs are already proven distinct under the complete projected row.

Source and further reading

This article addresses the problem raised by Brian G in β€œWhat is the difference between UNION and UNION ALL?” on Stack Overflow, licensed under CC BY-SA 3.0 . The question is the topic source. The explanations and examples here are newly authored from the database documentation, rather than reproduced from a community answer.

UNION (Transact-SQL) - SQL Server
Set Operators - UNION (Transact-SQL)
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-union-transact-sql?view=sql-server-ver17
7.4. Combining Queries (UNION, INTERSECT, EXCEPT)
7.4. Combining Queries (UNION, INTERSECT, EXCEPT) # The results of two queries can be combined using the set operations union, intersection, …
https://www.postgresql.org/docs/current/queries-union.html
SELECT
https://sqlite.org/lang_select.html

Author: Herman Schoenfeld