SQL UNION ALL – Merge of Queries with Example

Operator UNION ALL in SQL makes it possible to unify 2 query results and does not remove duplicities in queries. Operator returns records of both queries with no regard for existing duplicities. UNION ALL belongs to group called SET operators together with UNION, EXCEPT, INTERSECT

SQL UNION ALL Syntax

SELECT Column
FROM dbo.Table
WHERE Condition

  UNION ALL

SELECT Column
FROM dbo.Table
WHERE Condition

Syntaxe is again similar to all Set operators. This query returns all records from both queries with no regard for duplicities in the column.

UNION ALL Example

Assignment of the task will be same as for example with UNION operator. Let’s have a table with list of products:

Let’s do the unification of 2 queries again:

  • first query – records where Product Key (Primary key) is lower than 10
  • second query – records where Product Key (Primary key) is lower than 5

Both selections overlap. Product Keys <= 5 are selected twice. Operator should return all 15 records (10 from the first query, 5 from second one). UNION returned 10 records

SELECT [ProductKey], [EnglishProductName]
FROM [AdventureWorksDW2014].[dbo].[DimProduct]
WHERE [ProductKey]<=10

  UNION ALL

SELECT [ProductKey], [EnglishProductName]
FROM [AdventureWorksDW2014].[dbo].[DimProduct]
WHERE [ProductKey]<=5

The result is all 15 records (last 5 records are duplicities)

SQL UNION ALL

Rate this post
Category: SQL Commands

About Ing. Jan Zedníček - Data Engineer & Controlling

My name is Jan Zednicek, and I have been working as a freelance Data Engineer for roughly 10 years. During this time, I have been publishing case studies and technical guides on this website, targeting professionals, students, and enthusiasts interested in Data Engineering particularly on Microsoft technologies as well as corporate finance and reporting solutions. 🔥 If you found this article helpful, please share it or mention me on your website or Community forum

Leave a Reply

Your email address will not be published. Required fields are marked *