Skip to content
Related Articles

Related Articles

Improve Article

Union and Union All in MS SQL Server

  • Difficulty Level : Basic
  • Last Updated : 14 Aug, 2020

1. Union :
Union means joining two or more data sets into a single set. In SQL Server, Union is used to combine two queries into a single result set using the select statements. Union extracts all the rows that are described in the query.

Syntax –

Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.

query1 UNION query2

Union holds a few conditions before being used in a query. One such condition is that the rows to be extracted must come from the same columns from the tables.

Example –



select name, rollnumber 
from student 
UNION 
select name, rollnumber 
from marks


Table – Student
NameRollnumberCourse
Maya111CSE
Riya112Mech



Table – Marks
NameRollnumberMarks
Maya1118.9
Riya1127.8

Output –

NameRollnumberNameRollnumber
Maya111Maya111
Riya112Riya112

Two different tables are being used here for extraction of rows yet the column specified for extraction is the same for both. An error occurs if different columns are being used. The data type specified also must be the same for both the queries.



2. Union All :
A union is used for extracting rows using the conditions specified in the query while Union All is used for extracting all the rows from a set of two tables.

Syntax –

query1 UNION ALL query2

The same conditions are applicable to Union All. The only difference between Union and Union All is that Union extracts the rows that are being specified in the query while Union All extracts all the rows including the duplicates (repeated values) from both the queries.

My Personal Notes arrow_drop_up
Recommended Articles
Page :