Learn From - Interactive SQL



SQL UNION


The UNION is used to merge two or more tables having the same column names.

The Select statements used should have the same column names and the column names should be retrieved in the same order. Also the datatype for the columns should be the same in both the tables.

SQL UNION Syntax


SELECT column_name1, column_name2..
FROM table1
UNION
SELECT column_name1, column_name2..
FROM table2

Note: The executed result will show only distinct values only. To get duplicate values you need to use UNION ALL keyword.

SQL UNION ALL Syntax


SELECT column_name1, column_name2..
FROM table1
UNION ALL
SELECT column_name1, column_name2..
FROM table2

Note: The executed result will show all the duplicate values.

Below is shown the "Customers_USA" table:

CustomerID CustomerName EmailID
C001 Fredrick Jhonson FJhonson@yahoo.com
C003 George Clooney George@hotmail.com
C004 David Louis David@mail.com
C005 Jhonny Anderson Jhonny@gmail.com

Below is shown the "Customers_Australia" table:

CustomerID CustomerName EmailID
C001 Fredrick Jhonson FJhonson@yahoo.com
C003 George Clooney George@hotmail.com
C007 Henry King Henry@mail.com
C008 Robert Jhon Robert@gmail.com

SQL UNION Example


To merge tables with records from Customers_USA and Customers_Australia. All the unique records from both the tables are retrieved.

Text Editor below has the SQL Query, click the "View Result" button, to see the result.

Select Customers_USA.CustomerName, Customers_USA.EmailID
from Customers_USA
UNION
Select Customers_Australia.CustomerName, Customers_Australia.EmailID
from Customers_Australia

Note: The executed result contains only 6 records.

To merge tables with records from Customers_USA and Customers_Australia. The Executed Result will contain only Unique Records.

Select Customers_USA.CustomerName, Customers_USA.EmailID
from Customers_USA
UNION ALL
Select Customers_Australia.CustomerName, Customers_Australia.EmailID
from Customers_Australia

Note: The Executed Result contains only 8 records

SQL in Text Editor: