• 18. 1. 2020
  • Ing. Jan Zedníček - Data Engineer & Controlling
  • 0

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

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

My name is Jan Zedníček and I have been working as a freelancer for many companies for more than 10 years. I used to work as a financial controller, analyst and manager at many different companies in field of banking and manufacturing. When I am not at work, I like playing volleyball, chess, doing a workout in the gym.

🔥 If you found this article helpful, please share it or mention me on your website

Leave a Reply

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