SQL Day 17: Union and Union All

LO1: Purpose of Union and Union All

LO2: Difference between Union and Union All

LO3: Difference between Joins and Union

Prerequisite: Joins

Union and Union All is used to combine the result set of two or more queries.
To combine two results set, the column list in the select columns, data types, and order of the columns need to be same.

Let’s say we have the two table tblcustomer1 and tblcustomer2 with the identical columns in each table.



To combine these two result set into one we can use the Union All.

select * from tblcustomer1
Union All
select * from tblcustomer2



In the above screen, all the rows combined into one result set.

Now let’s try to use the Union only and observe the result set.

select * from tblcustomer1
Union
select * from tblcustomer2



In the above screen, the duplicate row is included only once and the result also gets sorted.

Note: In the case of Union, Duplicate rows only get removed from the result when all the columns contain the same the data.

If there is a difference between any column data then these rows will be included in the result.

Difference between Union and Union All

1. Union removes the duplicate rows from the result set where as Union All does not.
2. Union execution is slower than the Union All because Union has to perform the distinct 
sort to remove the duplicate rows.

Sorting the result of Union and Union All

To sort the result of Union and Union All, we can use the Order By clause at the last of the select statement. On using the Order By clause other than the last select statement then SQL Server will throw an error.

select * from tblcustomer1
Union All
select * from tblcustomer2
Order By Name desc



Difference between the Unions and Joins

Union combines rows from two or more tables, where as Join combine columns from two or more tables.

Union combines the result set of two or more select statement into one result set where as Join retrieve the data from two or more tables based on the logical relationship between the tables.

That’s all for today. Thank You.

Comments

Popular posts from this blog

SQL Day 11: Group By in SQL Server

JAVA Script Executor Code to Click on an Element

SQL Day 2: Creating, Altering and Dropping a Database