UNION ALL operator in SQL

The UNION ALL operator concatenates the results of two queries into a single result set. We control whether the result set includes duplicate rows:

SQL Syntax

SELECT column1, column2, ...
FROM table1
UNION ALL
SELECT column1, column2, ...
FROM table2;    

Example: Let's create two tables.

SQL

CREATE TABLE EmployeesA (
   EmployeeID INT,
    FirstName VARCHAR(20),
    LastName VARCHAR(20),
    Age int
);   

Load the data into the EmployeesA table.

SQL

insert into EmployeesA values
(1, "Ashish", "Goel", 25), 
(2, "Kirshan", "Gupta", 30),
(3, "Anjali", "Sharma", 25),
(4, "Manju", "Saini", 15),
(5, "Katrina", "Kaif", 18);  

By using the following query, we see the data from the EmployeesA table.

SQL

SELECT * FROM EmployeesA;  

Table: EmployeesA

EmployeeIDFirstNameLastNameAge
1AshishGoel25
2KirshanGupta30
3AnjaliSharma25
4ManjuSaini15
5KatrinaKaif18

Let’s create a EmployeesB table.

SQL

CREATE TABLE EmployeesB (
   EmployeeID INT,
    FirstName VARCHAR(20),
    LastName VARCHAR(20),
    Age int
);   

Load the data into the EmployeesB table.

SQL

insert into EmployeesB values
(3, "Anjali", "Sharma", 25),
(4, "Manju", "Saini", 15),
(5, "Katrina", "Kaif", 18),
(6, "Esha", "Dixit", 20),
(7, "Ankita", "Verma", 19), 
(8, "Meenakshi", "Chikkara", 35),
(9, "Alia", "Bhatt", 16);   

By using the following query, we see the data from the EmployeesB table.

SQL

SELECT * FROM EmployeesB;   

Table: EmployeesB

EmployeeIDFirstNameLastNameAge
3AnjaliSharma25
4ManjuSaini15
5KatrinaKaif18
6EshaDixit20
7AnkitaVerma19
8MeenakshiChikkara35
9AliaBhatt16

We can use the UNION ALL operator in SQL to concatenates the query into one set.

SQL

SELECT EmployeeID, FirstName, LastName, Age
FROM EmployeesA
UNION ALL
SELECT EmployeeID, FirstName, LastName, Age
FROM EmployeesB;   

The result of the above query is shown below:

EmployeeIDFirstNameLastNameAge
1AshishGoel25
2KirshanGupta30
3AnjaliSharma25
4ManjuSaini15
5KatrinaKaif18
3AnjaliSharma25
4ManjuSaini15
5KatrinaKaif18
6EshaDixit20
7AnkitaVerma19
8MeenakshiChikkara35
9AliaBhatt16