Backend & Databases Comparisonbeginner

UNION vs UNION ALL in SQL

UNION combines two query results and removes duplicate rows. UNION ALL keeps every row and is usually faster. See both on two small tables with real output.

5 min read

Our verdict in 30 seconds

UNION and UNION ALL both stack the results of two or more SELECT queries into one result. UNION removes duplicate rows, which needs extra work such as sorting or hashing. UNION ALL keeps every row, including duplicates, so it is usually faster. Use UNION when you need distinct rows, and UNION ALL when duplicates are impossible or you want to keep them.

On This Page

UNION vs UNION ALL in SQL differ in one thing: duplicates. Both combine the results of two or more SELECT queries into one list. UNION removes duplicate rows. UNION ALL keeps every row, duplicates included. Because removing duplicates takes extra work, UNION ALL is usually the faster of the two.

UNION vs UNION ALL: the difference table

Point UNION UNION ALL
Duplicate rows Removed Kept
Extra work Sort or hash to find duplicates None, rows are appended
Speed Slower on large results Usually faster
Row count Less than or equal to UNION ALL Sum of both queries
Result order Not guaranteed Not guaranteed
Use when You need distinct rows Duplicates are fine or impossible
Column rules Same number of columns, compatible types Same rules

In one line: UNION gives distinct rows; UNION ALL gives all rows.

Two small tables

A training institute keeps two lists: students in the Java batch and students in the SQL batch. Some students joined both.

CREATE TABLE java_batch (name VARCHAR(30), city VARCHAR(30));
CREATE TABLE sql_batch (name VARCHAR(30), city VARCHAR(30));

INSERT INTO java_batch VALUES
  ('Asha', 'Hyderabad'),
  ('Ravi', 'Warangal'),
  ('Meena', 'Hyderabad');

INSERT INTO sql_batch VALUES
  ('Ravi', 'Warangal'),
  ('Kiran', 'Vijayawada'),
  ('Asha', 'Hyderabad');
java_batch sql_batch
name city name city
Asha Hyderabad Ravi Warangal
Ravi Warangal Kiran Vijayawada
Meena Hyderabad Asha Hyderabad

Asha and Ravi appear in both tables.

UNION: duplicates removed

Question: list every student who has joined any batch.

SELECT name, city FROM java_batch
UNION
SELECT name, city FROM sql_batch
ORDER BY name;

Result (SQLite; MySQL returns the same rows):

name    city
Asha    Hyderabad
Kiran   Vijayawada
Meena   Hyderabad
Ravi    Warangal

Six rows went in, four came out. Asha and Ravi appear once each, because UNION treats two rows as duplicates when every column matches.

UNION ALL: duplicates kept

Question: list every enrolment, one row per batch joined.

SELECT name, city FROM java_batch
UNION ALL
SELECT name, city FROM sql_batch
ORDER BY name;
name    city
Asha    Hyderabad
Asha    Hyderabad
Kiran   Vijayawada
Meena   Hyderabad
Ravi    Warangal
Ravi    Warangal

All six rows are there. Asha and Ravi appear twice, once from each table.

Count them to see the difference clearly:

SELECT COUNT(*) AS rows_union FROM (
  SELECT name, city FROM java_batch
  UNION
  SELECT name, city FROM sql_batch
) AS u;
-- rows_union = 4

SELECT COUNT(*) AS rows_union_all FROM (
  SELECT name, city FROM java_batch
  UNION ALL
  SELECT name, city FROM sql_batch
) AS u;
-- rows_union_all = 6

Duplicates depend on the columns you select

UNION compares whole rows, so the columns you choose change what counts as a duplicate.

Select only the city:

SELECT city FROM java_batch
UNION
SELECT city FROM sql_batch
ORDER BY city;
city
Hyderabad
Vijayawada
Warangal

With UNION ALL, the same query returns six rows: Hyderabad three times, Vijayawada once and Warangal twice.

Now add a column that says which batch each row came from:

SELECT name, 'Java' AS course FROM java_batch
UNION
SELECT name, 'SQL' AS course FROM sql_batch
ORDER BY name, course;
name    course
Asha    Java
Asha    SQL
Kiran   SQL
Meena   Java
Ravi    Java
Ravi    SQL

Even with UNION, all six rows survive, because Asha, Java and Asha, SQL are different rows. Adding a label column like this is a common way to combine data from similar tables while keeping track of the source.

Common mistake: Using UNION "to be safe" when the two queries can never return the same row, for example orders from 2025 and orders from 2026. UNION still sorts or hashes everything to look for duplicates that cannot exist. Use UNION ALL there and skip the wasted work.

Rules for UNION and UNION ALL

  1. Same number of columns in every SELECT.
  2. Compatible data types in the same position: numbers with numbers, text with text. Some databases convert types for you, but do not rely on it.
  3. Column names come from the first query. In the label example, the second column is called course because the first SELECT named it.
  4. One ORDER BY at the end sorts the combined result.
  5. Each SELECT can have its own WHERE, GROUP BY and HAVING. If those two clauses confuse you, read WHERE vs HAVING in SQL.

Break rule 1 and you get an error:

SELECT name FROM java_batch
UNION
SELECT name, city FROM sql_batch;
SQLite: SELECTs to the left and right of UNION do not have the same number of result columns
MySQL:  ERROR 1222 (21000): The used SELECT statements have a different number of columns

Pro tip: Do not rely on the order of rows from UNION or UNION ALL. Without ORDER BY, the database may return rows in any order, and it can change when data or plans change. Always add ORDER BY when the order matters.

UNION vs JOIN: do not mix them up

Both "combine" tables, but in different directions.

UNION JOIN
Direction Stacks rows vertically Places columns side by side
Result gets More rows More columns
Needs Same number of columns A matching condition (ON)
Example Java batch list plus SQL batch list Students with their fee payments

If you need students next to their payments, you want a join. Inner join vs outer join covers that.

When to use each

Use UNION when

  • you need a distinct list from several sources, such as all unique email addresses from two sign-up tables
  • duplicates would be wrong in the report

Use UNION ALL when

  • the queries cannot overlap, such as data split by year or region
  • you want to keep duplicates, such as counting every enrolment
  • you are combining large results and performance matters

There are also INTERSECT (rows in both queries) and EXCEPT (rows in the first but not the second). SQLite, PostgreSQL and SQL Server support both, MySQL supports them from version 8.0.31, and Oracle traditionally uses MINUS for EXCEPT.

For freshers: how to answer in an interview

You can say this in about 30 seconds:

"UNION and UNION ALL combine the results of SELECT queries with the same number of columns. UNION removes duplicate rows, so it does extra work to find them. UNION ALL keeps all rows and is usually faster. I use UNION ALL unless I need distinct rows."

Then draw the two batch tables and show 4 rows against 6. Practise with SQL interview questions for freshers and keep the SQL commands list nearby. CodeBegun teaches SQL in the data analytics course, in Madhapur, Hyderabad and live online.

Interview note: A good follow-up answer: "If I need distinct rows from a single table, I use SELECT DISTINCT. UNION is for combining several queries." It shows you know which tool fits which job.

Frequently Asked Questions

Which is faster, UNION or UNION ALL?
UNION ALL is usually faster, because it simply appends the rows. UNION must find and remove duplicates, which means sorting or hashing the full result. On small results you will not notice; on millions of rows the difference can be large.
Does UNION remove duplicates within the same table?
Yes. UNION returns distinct rows from the whole combined result. If the first query alone returns the same row twice, UNION keeps only one copy of it.
Do the column names have to match in UNION?
No. The number of columns must match and the data types must be compatible, but the names can differ. The result uses the column names from the first SELECT.
What is the difference between UNION and JOIN?
UNION stacks rows from two queries on top of each other, so the result gets more rows. JOIN puts columns from two tables side by side, matched on a condition, so the result gets more columns.
Can I use ORDER BY with UNION?
Yes, once, at the very end. The ORDER BY sorts the combined result. Putting ORDER BY inside each SELECT is not allowed in most databases unless you wrap that part in brackets or a subquery.

Want to Build Your Career in Data Analytics with AI?

Join CodeBegun and train with working industry engineers — See the Data Analytics course in Hyderabad

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 5 December 2026 LinkedIn

More comparisons

View all
Chat with us