Skip to content
Related Articles

Related Articles

Improve Article

SQL | UNION Operator

  • Last Updated : 28 Aug, 2020

The UNION operator could be used to find the result-set or combination of two or more tables.

Terms and Condition for using UNION :

  • Each table used within UNION must have the same number of columns.
  • The columns must have same data types.
  • The columns in each table must be in the same order.

1. UNION Syntax :

SELECT columnnames FROM table1
UNION
SELECT columnnames FROM table2;

UNION operator provides only unique values by default. To find duplicate values, use UNION ALL :

2. UNION ALL Syntax :



SELECT columnnames FROM table1
UNION ALL
SELECT columnnames FROM table2;

Let’s assume we have two tables “Geeks1” and “Geeks2”;

Select * 
from Geeks1; 

IDNameSalaryCity
1234Khushi23000Jaipur
2345Megha24000Delhi
3456Komal24500Noida

Select * 
from Geeks2; 

IDNameSalaryCity
5678Vikram26000Gurugram
6789Mahesh24500Noida
7890Ashish25600Delhi

SQL UNION Example –
The below SQL statement finds the cities (only unique values) from both the “Geeks1” and the “Geeks2” table :

Example –

SELECT City 
FROM Geeks1

UNION

SELECT City 
FROM Geeks2
ORDER BY City; 

Output –



City
Delhi
Gurugram
Jaipur
Noida

SQL UNION ALL Example –
The below SQL statement finds the cities (duplicate values also) from both the “Geeks1” and the “Geeks2” table :

Example –

SELECT City 
FROM Customers

UNION ALL

SELECT City 
FROM Suppliers
ORDER BY City; 

Output –

City
Delhi
Delhi
Gurugram
Jaipur
Noida
Noida

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :