Open In App

SQL UNION ALL

Last Updated : 17 Nov, 2025
Comments
Improve
Suggest changes
2 Likes
Like
Report

UNION ALL Operator is used to combine the results of two or more SELECTstatements into a single result set. Unlike the UNION operator, which eliminates duplicate records and UNION ALL includes all duplicates. This makes UNION ALL it faster and more efficient when we don't need to remove duplicates.

Example: First, we create a demo SQL database and tables, on which we will use the UNION ALL command.

Table 1:

city-1

Table 2:

city-2

Query:

SELECT id, city FROM city_table1
UNION ALL
SELECT id, city FROM city_table2;

Output:

union-all

Syntax:

SELECT columns FROM table1
UNION ALL
SELECT columns FROM table2;

Examples of SQL UNION ALL

Let's look at some examples of the UNION ALL command in SQL to understand its working. First, let's create a demo SQL database and tables on which UNION ALL will be performed.

STUDENTS table:

table-1

TRIP_DETAIL Table:

table-2

Example 1: Single Field With Same Name

We want to combine the names from both the STUDENTS and TRIP_DETAIL tables, including all names, even if there are duplicates.

SELECT NAME FROM STUDENTS
UNION ALL
SELECT NAME FROM TRIP_DETAIL;

Output:

names

Example 2: Different Field Names

Suppose We want to combine the ROLL_NO from both tables and align the column names for consistency.

Query:

SELECT ROLL_NO AS Identifier FROM STUDENTS
UNION ALL
SELECT ROLL_NO AS Identifier FROM TRIP_DETAIL;

Output:

identifier

SQL UNION ALL With WHERE

You can use the WHERE clause with UNION ALL in SQL. The WHERE clause is used to filter records and is added after each SELECT statement

Example : SQL UNION ALL with WHERE

The following SQL statement returns the cities (duplicate values also) from both the "STUDENTS table" and the "TRIP_DETAIL Table" tables:

Query:

SELECT Country, Name FROM Emp1WHERE Name='Adi'UNION ALLSELECT Country, Name FROM Emp2WHERE Country='Ireland'ORDER BY Country;

Output:

where-unionall

SQL UNION All vs UNION

Here is the comparison between UNION ALL and UNION Operator:

FeatureUNION ALLUNION
Duplicate RecordsIncludes all duplicatesRemoves duplicate records
PerformanceFaster, as it doesn't check for duplicatesSlower, as it needs to eliminate duplicates
Use CaseWhen duplicates are acceptable or neededWhen duplicates need to be removed
SyntaxSELECT columns FROM table1 UNION ALL SELECT columns FROM table2;SELECT columns FROM table1 UNION SELECT columns FROM table2;
Memory UsageGenerally lower, since no extra processing for duplicatesHigher, due to additional steps for duplicate removal
Result SetCombined rows from all SELECT statements, including duplicatesCombined rows from all SELECT statements, without duplicates
ApplicabilityUseful for large datasets where performance is critical and duplicates are acceptableUseful when data integrity requires unique records in the result set

Explore