SQL UNION Operator

Introduction

  • The SQL UNION operator combines the result-set of two or more SELECT statements.
  • To use UNION operator, each SELECT statement within the UNION should have the same number of columns of similar data types and the column in each SELECT statement should be in same order.
  • The UNION operator selects only distinct values but ALL keyword is used with UNION to allow duplicate values.
Syntax:
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;

Syntax with ALL keyword:
SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2;

Example : Consider the following tables.

Table1 : 'Professors'

Prof_IDProf_NameCityCountry
1ThomasHamiltonNew Zealand
2AlbertPerthAustralia
3BushSydneyAustralia
4ClintonSydneyAustralia
5FlemingHamiltonNew Zealand

Table2 : 'Students'

Stud_IDStud_NameCityCountry
1MarkLondonEngland
2AlexParisFrance
3BobSydneyAustralia
4JayaDelhiIndia
5SurendraBarodaIndia

1. Write a query to select different cities from table1 and table2.

SELECT City FROM  Professors
UNION
SELECT City FROM Students;

The result is shown in the following table.

City
Baroda
Delhi
Hamilton
London
Paris
Sydney

2. Write a query to select cities by using ALL keyword.

SELECT City FROM  Professors
UNION ALL
SELECT City FROM Students;

The result is shown in the following table.

City
Hamilton
Perth
Sydney
Sydney
Hamilton
London
Paris
Sydney
Delhi
Baroda