Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 38/ 160
02. Aggregations, Functions & Data Manipulation

Set Operations (UNION vs UNION ALL)

Stack result sets and choose between deduplicating UNION and faster UNION ALL.

BeginnerUNION · UNION ALL3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Both put one result under another. UNION also deletes repeated rows; UNION ALL doesn't.

Think of it like…

Merging two guest lists: UNION ALL staples the pages together; UNION also reads through the combined list and crosses out anyone who appears twice.

Where you’ve seen it

Combining this year's and last year's order tables into one report: the rows can't overlap, so UNION ALL is correct and avoids sorting millions of rows that UNION would do for nothing.

Words you’ll hear

Set operation
Combines whole result sets: UNION, INTERSECT, EXCEPT.
Column alignment
Columns are matched by position, not by name.
Deduplication
UNION's extra step that removes identical rows.
Result column names
Taken from the first query.

Visual diagram

Loading interactive diagram

Theory & example queries

What each one does

UNION ALL simply appends the second result to the first. UNION does the same, then removes duplicate rows from the entire combined result, including duplicates that came from the same query. For this comparison, two NULLs count as equal.

To deduplicate, the database has to sort or hash every row, which needs memory and may spill to disk on big results. If the inputs can't overlap (different years, different source systems with a source column), that work is wasted.

Combining two years of ordersQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  id,3  amount4FROM5  orders_20256UNION ALL7SELECT8  id,9  amount10FROM11  orders_2026;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Orders from both year tables4 sample rows
Orders from both year tables
idamount
10011200
1002899
20011450
2002675

Note: Illustrative rows from two compatible SELECTs; UNION ALL preserves input duplicates and does not sort unless ORDER BY is added.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Use UNION ALL by default; UNION only when duplicates must go.

The rules for combining queries

Every query must return the same number of columns, and columns are paired by position, so SELECT name, email combined with SELECT email, name silently mixes the two up. Types must be compatible; add explicit casts if one side is text and the other is a number.

The result takes its column names from the first query. ORDER BY and LIMIT apply to the whole combined result and go at the very end; to sort or limit one branch, wrap it in parentheses or a subquery.

Labelling where each row came fromQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  'customer' AS source,3  email4FROM5  customers6UNION ALL7SELECT8  'lead',9  email10FROM11  leads12ORDER BY13  email;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Emails labeled by source4 sample rows
Emails labeled by source
sourceemail
leadasha@example.com
customerasha@example.com
customerkabir@example.com
leadmei@example.com

Note: The repeated email demonstrates that UNION ALL keeps duplicates; row values are sample data.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Match columns by position, and put ORDER BY once at the end.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Shape

Line up the columns

Make each query return the same columns in the same order, with compatible types. Cast where needed.

SQL at this stepReadable preview
1SELECT id,2  email … /3SELECT id,4  email …
What to watch at this step
Matched by
position
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

UNION and UNION ALL stack the results of two queries on top of each other. UNION ALL keeps every row; UNION then removes duplicate rows from the combined result. Both require the same number of columns with compatible types, matched by position.

Why it matters: UNION's deduplication costs a sort or hash over the whole result, and on large data that can turn a fast query slow. Using UNION when you don't need deduplication is one of the most common performance mistakes in SQL, and a frequent interview question.

When to reach for it

  • Merging the same kind of data from several tables (yearly partitions, regional tables)
  • Building one distinct list from multiple sources with UNION
  • Adding a source label column so you can tell where each row came from

When to avoid or be careful

  • UNION when the inputs can't overlap; it's pure overhead
  • Relying on column names to line up; only position matters
  • Using UNION to hide duplicates that come from a bad join

UNION ALL vs UNION vs a single query

UNION ALL
Best for: Combining sources that can't overlap, or where duplicates are real data

Strengths: Cheapest: just appends rows.

Watch out: Keeps duplicates, so you must be sure that's what you want.

UNION
Best for: Building a distinct list from several sources (all emails across tables)

Strengths: Each row appears once.

Watch out: Sorts or hashes the whole result; can be slow on big data.

One query with OR / IN
Best for: Combining conditions on the same table

Strengths: One scan, no set operation at all.

Watch out: Not possible when the data lives in different tables.

Interview signals & numbers to know

When this topic comes up

  • “UNION vs UNION ALL”
  • “Combine results from two tables”
  • A slow query with a large sort step
  • “Each query in a UNION must have the same number of columns”
  • Distinct list across sources

Benchmarks & rules of thumb

0 -
extra work for UNION ALL
O(n log n) -
typical cost of UNION's sort-based deduplication
1st query -
decides the column names

Common mistakes & follow-ups

Common interview mistakes

  • Using UNION out of habit and paying for a sort over millions of rows.
  • Writing the columns in a different order in the second query, which silently mixes up the data.
  • Putting ORDER BY inside the first query and expecting it to sort only that part.

Likely interviewer follow-ups

  • Why is UNION ALL faster than UNION?
  • Does UNION remove duplicates that come from the same query?
  • How would you find rows that are in one table but not in another using set operations?
Interview tip: Give the one-line difference, then the performance reason (UNION deduplicates with a sort or hash), then say you default to UNION ALL. That's the full answer interviewers look for.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Set Operations (UNION vs UNION ALL) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Regular Expressions in SQL (REGEXP_MATCHES, REGEXP_REPLACE, ~)
Next topic
Set Differences & Intersections (INTERSECT, EXCEPT)