Complete Guide: Union all vs Union operators in SQL Server

Complete Guide: Union all vs Union operators in SQL Server
SQL Server has 2 operators called Union All and Union that combine the result-set of two or more SELECT statements. The difference between Union All and Union operators is that Union All will ‘not remove the duplicate rows’ from the combined result-set, on the other hand Union operator will ‘remove the duplicate rows’ from the combined result-set.
Demo Database
To understand the difference – Union All vs Union, I will take the help of a demo database. There are 2 tables in this database which are shown below:

1. “Harward” table:

IdNameAgeCourse
1John Travolta20Computer Graphics
2Mary Jones21Advanced Maths
3Jacobs22Motion Physics

2. “MIT” table:

IdNameAgeCourse
1Mena Suvari25MBA
2John Travolta30PHD

Note: Note: Both tables have a duplicate student by the name of ‘John Travolta’.

Now let us select the data from these 2 tables using Union and Union All operators.

SQL Union All

sql union allRun the following SQL Union All query statement to combine the results from the 2 tables (Harward & MIT).
Select Name, Age From Harward 
Union All
Select Name, Age From MIT

You will see the result which is shown below:

NameAgeCourse
John Travolta20Computer Graphics
Mary Jones21Advanced Maths
Jacobs22Motion Physics
Mena Suvari25MBA
John Travolta30PHD

You can clearly see that Union All presented you with all the records from the 2 tables. That is, the student named ‘John Travolta’ is shown from each of these 2 tables.

When a user forgets his/her password then he/she should be able to reset the password. Check How this feature is created – Creating Password Reset feature in ASP.NET Core Identity

SQL Union

SQL UnionNow run the same query with SQL Union operator.
Select Name, Age From Harward 
Union
Select Name, Age From MIT

The result in this case is:

NameAgeCourse
John Travolta20Computer Graphics
Mary Jones21Advanced Maths
Jacobs22Motion Physics
Mena Suvari25MBA

See that the SQL Union has removed the duplicate entry of the student named ‘John Travolta’, from the result-set.

Points to note

1. The ‘Union’ operator effectively does a SELECT DISTINCT on the results set. If you know that all the records are unique then use Union All instead, since it gives faster results.

2. Union & Union All can be used in place of SQL Joins as they may be faster in certain situations.

3. Inner queries can be rewritten using Union and Union All.

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate

Leave a Reply

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