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.
Recommended Posts:
- Union and Union All in MS SQL Server
- Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
- SQL | Union Clause
- Difference between JOIN and UNION in SQL
- SQL | BETWEEN & IN Operator
- SQL | NOT Operator
- SQL | Concatenation Operator
- SQL | Alternative Quote Operator
- Difference between = and IN operator in SQL
- SQL | MINUS Operator
- SQL | Procedures in PL/SQL
- SQL | Difference between functions and stored procedures in PL/SQL
- Difference between T-SQL and PL-SQL
- Difference between SQL and T-SQL
- MySQL | Operator precedence
- PLSQL : || Operator
- Mitigation of SQL Injection Attack using Prepared Statements (Parameterized Queries)
- SQL | SELECT Query
- SQL | Distinct Clause
- SQL | WHERE Clause
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.

