Open In App

Union and Union All in MS SQL Server

Last Updated : 17 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In MS SQL Server, the UNION and UNION ALL operators are used to combine the result sets of two or more SELECT statements into a single result set. This allows you to retrieve data from multiple tables or views and combine it into a single dataset.

The primary difference between UNION and UNION ALL is that UNION removes duplicate rows from the result set, while UNION ALL includes all rows, including duplicates.

UNION Operator in MS SQL Server

Union means joining two or more data sets into a single set. In SQL Server, the UNION operator 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:

The syntax of the UNION operator in MS SQL Server is:

SELECT column1, column2, ... FROM table1
UNION
SELECT column1, column2, ... FROM table2;

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

Let’s look at some examples of the UNION operator in MS SQL Server

SELECT name, rollnumber
FROM student
UNION
SELECT name, rollnumber
FROM marks;

Table Student

Name Rollnumber Course
Maya 111 CSE
Riya 112 Mech

Table Marks

Name Rollnumber Marks
Maya 111 8.9
Riya 112 7.8

Output:

Name Rollnumber Name Rollnumber
Maya 111 Maya 111
Riya 112 Riya 112

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.

UNION ALL in MS SQL Server

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

The syntax to use UNION ALL in MS SQL Server is:

SELECT column1, column2, ... 
FROM table1
UNION ALL
SELECT column1, column2, ...
FROM table2;

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.

Example

Let’s look at some examples of the UNION ALL operator in MS SQL Server

SELECT Name, Rollnumber, 'Student' AS Type
FROM Student
UNION ALL
SELECT Name, Rollnumber, 'Marks' AS Type
FROM Marks;

Output:

Name Rollnumber Type
Maya 111 Student
Riya 112 Student
Maya 111 Marks
Riya 112 Marks

As you can see, UNION ALL operator also keeps duplicate values in it’s result set.



Next Article
Article Tags :

Similar Reads