SQL | UNION Operator

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; 

ID Name Salary City
1234 Khushi 23000 Jaipur
2345 Megha 24000 Delhi
3456 Komal 24500 Noida

Select * 
from Geeks2; 

ID Name Salary City
5678 Vikram 26000 Gurugram
6789 Mahesh 24500 Noida
7890 Ashish 25600 Delhi

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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.