SQL- UNION AND UNION ALL-Examples

sql-union
Spread the love

SQL UNION and UNION ALL are used to combine result sets of two or more SELECT statements.

Syntax:

<SELECT STATEMENT>
UNION / UNION ALL
<SELECT STATEMENT>

When we use only UNION , duplicate values are removed.
When we use UNION ALL, ALL values are present and duplicates are not removed.

EXAMPLE:

To give a demo of UNION, we are going to use table ‘PLAYERS_LOCATION’

Now lets use UNION,

SELECT CITY
FROM PLAYERS_LOCATION
UNION 
SELECT CITY
FROM PLAYERS_LOCATION ; 

As you can see , we use UNION operator to combine the result set of two similar SELECT Statement.
There are no duplicates in the final result set.

Now we will use UNION ALL,

SELECT CITY
FROM PLAYERS_LOCATION
UNION ALL
SELECT CITY
FROM PLAYERS_LOCATION

After using UNION ALL, we can see there are duplicates.

Thanks For Reading!

Read More : Learn SQL Fast