SQL Server / Basic / Lesson 7
Combine result sets with UNION
Choose between preserving rows and removing duplicates when combining two reports.
On this page
Lesson goals
- Distinguish UNION ALL from UNION.
- Predict duplicate handling in a synthetic result.
- Verify compatible columns and final ordering.
- Choose UNION or UNION ALL from the intended duplicate and event-identity policy.
- Align branch columns, types and final ordering in a T-SQL set query.
Define what one row means
Two branches of a report might list items from different sources. UNION ALL combines their rows and preserves duplicates; UNION combines them and removes duplicate result rows. Choose the operation from the business meaning, not from an assumption that duplicate-looking rows are always mistakes. Before combining sources, check that corresponding columns describe compatible concepts and types and that the intended row grain is the same.
Preserve both occurrences
The following illustrative T-SQL uses inline synthetic values in a disposable SQL Server 2019 lab. Each branch contains Pen once, so UNION ALL retains two Pen rows. The explicit final ORDER BY controls presentation. The public course does not connect to a server or execute this example, and actual client formatting depends on the environment.
SELECT item FROM (VALUES (N'Pen'), (N'Notebook')) AS a(item)
UNION ALL
SELECT item FROM (VALUES (N'Pen'), (N'Folder')) AS b(item)
ORDER BY item;
The declared inputs contain four rows: Folder, Notebook, Pen, and Pen in the specified ordering. Both Pen occurrences remain because UNION ALL does not remove duplicate result rows.
Remove duplicate result rows
The second query changes only the set operator. UNION removes the duplicate complete result row, so one Pen remains for this one-column example. If a source label or another differing column is included, two Pen rows may no longer be duplicates as complete rows. Inspect every selected column before deciding that deduplication matches the business requirement.
SELECT item FROM (VALUES (N'Pen'), (N'Notebook')) AS a(item)
UNION
SELECT item FROM (VALUES (N'Pen'), (N'Folder')) AS b(item)
ORDER BY item;
The declared inputs yield three distinct item values: Folder, Notebook, and Pen. This is derived from the fixture, not a measured server result. The final order is explicit.
Check types and ordering
Each branch must return the same number of expressions in compatible positions. SQL Server applies its documented type and collation rules when combining them, so test the actual schema and values rather than assuming that similar display text is identical. The final ORDER BY applies to the combined result. Add a stable tie-breaker when a report requires deterministic ordering among equal values.
Reconcile source and output
Test a row present in both sources, a row unique to each source, and relevant missing or case-variant values under the deployed collation. Compare the number of input rows and output rows with a hand calculation. If each occurrence represents a separate transaction, retain an identifying column or use UNION ALL; removing duplicate rows can hide real activity. Measure performance only after confirming correctness.
Align result shapes before combining
UNION and UNION ALL stack compatible query results vertically. Each branch must return the same number of columns in corresponding positions, and SQL Server must be able to resolve compatible types for each position. A name in the first result position is not automatically matched to a same-named column in another position; the order of expressions determines alignment. State what one output row represents, its units and its column types before combining sources.
For example, one branch returning Item, Quantity and another returning Quantity, Item may have the same number of columns but an incompatible or misleading mapping. Explicit projections and casts make the contract reviewable. The result column names are taken from the first query; labels do not change the positional mapping. All scenarios here use synthetic inputs and reasoned outputs. No SQL Server instance was accessed and snippets are not qualified runnable programs.
Choose bag or distinct-row semantics
UNION ALL preserves rows from every branch, including duplicates. If each source returns one Pen row, the combined output contains two Pen rows. UNION removes duplicate complete output rows, so those identical one-column rows become one. This is a semantic choice, not simply a performance switch. When each row represents a separate sale or event, equal displayed values can still correspond to distinct business events and deduplication may lose information.
UNION compares the complete selected row. Adding a source column with values A and B makes (Pen,A) and (Pen,B) different rows, so both survive UNION. Conversely, projecting away a unique event key can make independent events appear equal. Decide whether identity, source and value are part of the intended result before choosing a set operator. Count and inspect complete rows, not only a single visible field.
Control conversion and missing values
SQL Server resolves a common type for corresponding expressions according to type compatibility and precedence. Mixing a numeric branch with nonnumeric text can force a conversion that fails; mixing compatible numeric types can change precision or scale. Use explicit casts and test the actual values when a stable output contract matters. Do not assume a column alias converts the underlying value or that the same type name implies identical units.
NULL is a value marker in the output and participates in duplicate elimination for set operations according to SQL Server’s distinct-row rules. Two rows that are otherwise identical and both contain NULL can collapse under UNION; UNION ALL retains both. This differs from interpreting NULL = NULL in a WHERE predicate. Test the set operation itself rather than transferring a predicate truth-table assumption blindly.
Order the combined result deliberately
Neither UNION nor UNION ALL guarantees branch order or final presentation order. Use a final ORDER BY on the combined query when sequence matters; an observed concatenation order on a small fixture is not a contract. In SQL Server the ORDER BY for a UNION query belongs after the combined branches and its expressions must satisfy the set-query rules. Include a stable tie breaker if the consumer depends on the order of otherwise equal rows.
A source label can support a desired presentation, but adding it also changes the full row used by UNION for duplicate elimination. If the business wants one distinct item with a list of sources, design that aggregation explicitly rather than relying on a label that makes rows different. Compare the output keys and counts after the final projection. A later ORDER BY sorts the result but does not restore events that UNION already removed.
Test normal and boundary cases
Use two small synthetic sources containing an overlapping item, a source-specific item and a NULL. Predict both UNION and UNION ALL outputs, then test a source-label variant and an empty branch. Verify column alignment, types, duplicate policy and final ordering independently. Equal row counts do not prove the same rows were returned; compare the actual complete tuples and business identifiers.
A set operator can combine data from separate tables or query branches without joining them by a key. A JOIN answers a different question by matching rows horizontally and can multiply combinations. Choose the construct from the intended row meaning. For any operational query, check permissions, collation and conversion behavior in the actual SQL Server version and isolated environment; the small examples establish logic, not production performance.
20 worked examples
1. UNION ALL duplicate
Problem: How many Pen rows survive from two branches?
- Each branch contributes one row with the same item.
- UNION ALL preserves both branch rows.
SELECT N'Pen' AS Item UNION ALL SELECT N'Pen';
Pen; Pen
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Equal displayed values can represent two independent input events.
2. UNION duplicate
Problem: How many identical Pen rows survive UNION?
- Both branches produce the same one-column row.
- UNION removes the duplicate complete row.
SELECT N'Pen' AS Item UNION SELECT N'Pen';
Pen
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Distinct-row semantics collapse identical output tuples.
3. Different items
Problem: What survives when the branches produce different values?
- The two strings are distinct under the stated ordinary comparison.
- UNION has no duplicate complete row to remove.
SELECT N'Pen' AS Item UNION SELECT N'Pencil' ORDER BY Item;
Pen; Pencil
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Both distinct items remain and the final ORDER BY specifies their order.
4. Source label
Problem: Why do two Pen rows survive UNION with source labels?
- The first complete row has source A.
- The second complete row has source B.
SELECT N'Pen' AS Item, N'A' AS Source UNION SELECT N'Pen', N'B' ORDER BY Source;
Pen | A; Pen | B
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: UNION compares both output columns, so these rows differ.
5. Same source label
Problem: What happens when item and source both match?
- Both branches yield identical two-column rows.
- UNION removes the repeated tuple because both selected values match in the two branches.
SELECT N'Pen' AS Item, N'A' AS Source UNION SELECT N'Pen', N'A';
Pen | A
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Duplicate elimination applies to every selected column.
6. Distinct events
Problem: Why might UNION lose a separate sale?
- The projection omits the distinct SaleId values.
- Both projected rows are therefore identical.
-- Sale 101 and sale 102 both have Item=Pen.
SELECT Item FROM (VALUES (101,N'Pen'),(102,N'Pen')) AS s(SaleId,Item) WHERE SaleId=101
UNION
SELECT Item FROM (VALUES (101,N'Pen'),(102,N'Pen')) AS s(SaleId,Item) WHERE SaleId=102;
One Pen row
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: UNION eliminates a displayed duplicate even when the source events differ.
7. Preserve event keys
Problem: How can the two sales remain distinct?
- The two output tuples contain different sale identifiers.
- UNION sees distinct complete rows.
SELECT SaleId,Item FROM (VALUES (101,N'Pen'),(102,N'Pen')) AS s(SaleId,Item) WHERE SaleId=101
UNION
SELECT SaleId,Item FROM (VALUES (101,N'Pen'),(102,N'Pen')) AS s(SaleId,Item) WHERE SaleId=102 ORDER BY SaleId;
101 | Pen; 102 | Pen
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Keeping the event key preserves the distinction in the projected result.
8. NULL under UNION
Problem: How many NULL rows remain after UNION?
- Both branches return a one-column NULL row of compatible type.
- UNION eliminates duplicate complete rows.
SELECT CAST(NULL AS int) AS Value UNION SELECT CAST(NULL AS int);
One NULL row
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Set duplicate handling treats these output rows as duplicates.
9. NULL under UNION ALL
Problem: How many NULL rows remain with UNION ALL?
- Each branch contributes a row.
- UNION ALL does not remove duplicate rows.
SELECT CAST(NULL AS int) AS Value UNION ALL SELECT CAST(NULL AS int);
Two NULL rows
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Preserving both rows is independent of their missing values.
10. Empty branch
Problem: What if one branch returns no rows?
- The first branch’s predicate is false.
- The second branch contributes one Pencil row.
SELECT Item FROM (VALUES (N'Pen')) AS a(Item) WHERE 1=0 UNION ALL SELECT N'Pencil';
Pencil
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: An empty branch adds nothing to the combined result.
11. Column position
Problem: How are the two values aligned?
- The first expression in each branch occupies the first result column.
- The second expression in each branch occupies the second result column.
SELECT N'Pen' AS Item, 2 AS Quantity UNION ALL SELECT N'Pencil', 3;
Pen | 2; Pencil | 3 (order unspecified)
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Set operations align expressions by position, not by their source labels.
12. First-branch names
Problem: Which output column name is used?
- The first query supplies the combined result’s column name.
- The second alias does not rename the combined output column.
SELECT 1 AS FirstName UNION ALL SELECT 2 AS SecondName;
Column name FirstName; values 1 and 2.
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Aliases label positions but do not alter positional alignment.
13. Mismatched columns
Problem: Can branches return different column counts?
- The first branch returns two expressions.
- The second branch returns only one expression.
SELECT 1 AS Id, N'Pen' AS Item UNION ALL SELECT 2;
The query fails because the branches have different column counts.
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: A set operator requires corresponding result positions in every branch.
14. Type conversion failure
Problem: What happens when text cannot convert to the selected numeric type?
- SQL Server resolves a common type using type precedence.
- The nonnumeric string cannot be converted to int.
SELECT 1 AS Value UNION ALL SELECT 'not-a-number';
The query fails converting the text to int.
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Corresponding columns need compatible values as well as a compatible result type.
15. Explicit compatible type
Problem: How can two textual codes share an explicit type?
- Both branches explicitly produce nvarchar(10).
- Each code fits the declared length and remains a text value in the combined result.
SELECT CAST(N'01' AS nvarchar(10)) AS Code UNION ALL SELECT CAST(N'A2' AS nvarchar(10));
01; A2 (order unspecified)
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: The common type is deliberate and does not require numeric conversion.
16. Final ordering
Problem: How is the combined item order requested?
- Both rows survive UNION ALL.
- The final ORDER BY sorts the combined output by Item.
SELECT N'Pencil' AS Item UNION ALL SELECT N'Pen' ORDER BY Item;
Pen; Pencil
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: A final order is the query contract rather than an assumed branch order.
17. Duplicates inside one branch
Problem: Does UNION remove duplicates already within a branch?
- The first branch produces two identical Pen rows.
- UNION applies duplicate elimination to the combined result.
SELECT Item FROM (VALUES (N'Pen'),(N'Pen')) AS a(Item) UNION SELECT N'Pencil';
Pen; Pencil (order unspecified)
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Distinct-row semantics apply across and within branch outputs.
18. UNION ALL multiplicity
Problem: How many rows survive duplicates within and across branches?
- The first branch contributes two Pen rows.
- The second branch contributes one more Pen row.
SELECT Item FROM (VALUES (N'Pen'),(N'Pen')) AS a(Item) UNION ALL SELECT N'Pen';
Three Pen rows
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: UNION ALL preserves the full input multiplicity.
19. Different units
Problem: Why are aligned numbers not automatically comparable?
- The values occupy the same numeric output position.
- The query does not convert or identify their different units.
-- Branch A: 1 kilogram.
-- Branch B: 1000 grams.
SELECT 1 AS Weight UNION ALL SELECT 1000;
1; 1000 (order unspecified); units remain ambiguous.
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: A shared SQL type does not establish a shared measurement contract.
20. UNION versus JOIN
Problem: How many rows does each operation express for two sources?
- Stacking includes every input row from both sources.
- Joining pairs only rows whose item values match.
-- Source A: Pen, Pencil. Source B: Pen.
-- UNION ALL stacks three rows.
-- An equality JOIN on Item matches only the two Pen inputs.
UNION ALL yields 3 rows; equality JOIN yields 1 matched pair.
The synthetic fixture and result are reasoned; SQL Server was not accessed.
Why this result follows: Vertical combination and horizontal matching answer different questions.
Common errors and fixes
A report loses a real occurrence.
- Why it happens
- UNION removed identical result rows that represented separate events.
- How to fix it
- Use UNION ALL or include the required identity according to the report contract.
- Prevent it next time
- Test repeated business events in both sources.
Two expected duplicates remain after UNION.
- Why it happens
- Another selected column differs, so the complete result rows are distinct.
- How to fix it
- Review the intended grain and selected columns.
- Prevent it next time
- Compare all output columns in duplicate tests.
The combined result order changes.
- Why it happens
- The query relied on branch order without a final ORDER BY.
- How to fix it
- Specify the required final ordering and tie-breaker.
- Prevent it next time
- Include ordering in the report contract.
20 practice exercises
1. How many Pen rows does the UNION ALL fixture return?
Show hint
Count the contribution from each branch without deduplication.
Show worked solution
Two. Each input branch contributes one Pen row and UNION ALL preserves both.
Each branch contributes one Pen row and UNION ALL preserves both, so the result contains two Pen rows. Equal item text does not erase either branch contribution.
Check your solution
- The result contains two rows.
- Both rows contain Pen.
2. Why can adding a source column make two Pen rows survive UNION?
Show hint
Compare the entire selected tuple after adding the source.
Show worked solution
UNION compares the complete selected rows. If their source values differ, the rows are distinct even though the item value is the same.
If one row is (Pen,A) and the other is (Pen,B), the source values differ. UNION removes only duplicate complete rows, so both survive even though their Item values match.
Check your solution
- The source values differ.
- Both complete rows survive UNION.
3. Two branches each return Pen. How many rows does UNION ALL return?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
It returns two Pen rows because UNION ALL preserves one row from each branch. Equal displayed values do not imply that the two input events are the same business event.
Check your solution
- Two rows remain
- Both rows contain Pen
4. Two branches each return Pen. How many rows does UNION return?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
It returns one Pen row because the complete projected rows are identical. Use UNION only when distinct output tuples are intended; it can hide separate events if their identifiers were projected away.
Check your solution
- One row remains
- Identical tuples are deduplicated
5. One branch returns (Pen,A) and the other (Pen,B). Does UNION remove either?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
No. The source labels differ, so the complete rows are distinct even though the item is the same. Decide whether the source belongs in the deduplication contract.
Check your solution
- Both rows remain
- Source values differ
6. Two sales have different SaleId values but both project only Pen. What can UNION lose?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
It collapses the two identical projected Pen rows into one, hiding that two sales occurred. Preserve the event identifier or use UNION ALL when both events belong in the result.
Check your solution
- Projection removes SaleId
- UNION can collapse separate sales
7. One branch returns two Pen rows and another returns one. How many rows under UNION ALL?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
All three rows remain because UNION ALL preserves duplicates within and across branches. Use an explicit event key if consumers must distinguish their identities.
Check your solution
- Three rows remain
- Multiplicity is preserved
8. One branch is empty and the other returns Pencil. What does UNION ALL produce?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
It produces one Pencil row because the empty branch contributes nothing. Confirm the empty branch condition is intentional rather than inferring a data-source failure from the combined result alone.
Check your solution
- One Pencil row remains
- Empty branch adds no rows
9. A branch selects Item, Quantity and another selects Quantity, Item. What must be corrected?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
Align corresponding expressions in the same positions and verify compatible types and units. Set operations do not match values by column name; an alias cannot repair reversed semantic positions.
Check your solution
- Column positions must align
- Verify types and units
10. The first branch returns two columns and the second returns one. Can UNION ALL combine them?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
No. Each branch must have the same number of corresponding expressions. Add or remove a deliberately defined output column and ensure the resulting types and meanings are compatible.
Check your solution
- Column counts must match
- Define each corresponding position
11. The first branch aliases a column Item and the second aliases it Product. Which output name is used?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
The combined result uses the first query’s output column name Item. The second alias does not change positional alignment or create a separate Product column.
Check your solution
- Output name is Item
- Alignment remains positional
12. A numeric branch returns 1 and another returns text not-a-number. Why can UNION ALL fail?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
SQL Server resolves a common type according to type precedence, which can require converting the text to int. The nonnumeric text cannot make that conversion; choose and validate an explicit common type.
Check your solution
- Conversion can target int
- Nonnumeric text fails conversion
13. How can code strings 01 and A2 be combined without treating them as numbers?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
Explicitly cast both branches to an appropriate nvarchar length and verify the values fit. This preserves the leading zero and avoids an unintended numeric conversion.
Check your solution
- Both branches use a text type
- Leading zero is preserved
14. Two branches return NULL in the same single column. Compare UNION and UNION ALL.
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
UNION returns one NULL row after duplicate elimination; UNION ALL returns two rows. Set duplicate treatment should not be confused with NULL equality in a WHERE predicate.
Check your solution
- UNION returns one row
- UNION ALL returns two
15. Does UNION ALL guarantee that rows from branch A appear before branch B?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
No. Without a final ORDER BY, SQL Server does not guarantee presentation order. Add an appropriate source and unique tie breaker if order is a requirement, while considering how labels affect duplicate semantics.
Check your solution
- Branch order is not guaranteed
- Use a final ORDER BY
16. A source label is added to a UNION query for ordering. How can it change the result?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
The label becomes part of each complete row, so otherwise equal items from different sources may no longer be duplicates. Decide the desired identity and aggregation before adding the label.
Check your solution
- Source label changes the tuple
- Different labels can both survive
17. Branch A returns weight 1 kilogram and B returns 1000 grams in the same numeric column. What is missing?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
The values need a shared unit or an explicit unit column and conversion policy. A compatible SQL numeric type does not make their physical meanings equivalent.
Check your solution
- Define a common unit
- Convert or label values explicitly
18. Source A contains Pen and Pencil; source B contains Pen. How many rows under UNION ALL and equality JOIN?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
UNION ALL stacks all three input rows, while an equality JOIN produces one matching Pen pair. Choose according to whether the result represents individual inputs or matched pairs.
Check your solution
- UNION ALL yields 3 rows
- Equality JOIN yields 1 pair
19. Two results both contain three rows. Why is that insufficient to prove they match?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
One result can have a missing tuple and an extra tuple that cancel in the count. Compare complete rows or business keys as well as counts, respecting the intended duplicate multiplicity.
Check your solution
- Counts can match despite differences
- Compare tuples and multiplicity
20. A combined query needs a deterministic item order with ties. What should be specified?
Show hint
Trace complete output tuples, branch multiplicity and positional alignment.
Show worked solution
Add a final ORDER BY with the required item order and a stable unique tie breaker if rows must have a reproducible sequence. Do not rely on the order in which branches happen to appear.
Check your solution
- Specify final ORDER BY
- Define a stable tie breaker
Key takeaways
- UNION ALL preserves rows; UNION removes duplicate complete rows.
- Match column meaning and compatible types across branches.
- Specify final ordering and test the report grain.
- UNION removes duplicate complete rows; UNION ALL preserves multiplicity.
- Set operations align columns by position and resolve compatible result types.
- A final ORDER BY is required when output sequence matters.