Set Operations (UNION vs UNION ALL)
Stack result sets and choose between deduplicating UNION and faster UNION ALL.
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
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.
SELECT id, amountFROM orders_2025UNION ALLSELECT id, amountFROM orders_2026;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Orders from both year tables4 sample rows
| id | amount |
|---|---|
| 1001 | 1200 |
| 1002 | 899 |
| 2001 | 1450 |
| 2002 | 675 |
Note: Illustrative rows from two compatible SELECTs; UNION ALL preserves input duplicates and does not sort unless ORDER BY is added.
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.
| id | name | city | |
|---|---|---|---|
| 1 | Maya | maya@example.com | Pune |
| 2 | Ravi | ravi@example.com | Delhi |
| 3 | Noor | noor@example.com | Mumbai |
SELECT 'customer' AS source, emailFROM customersUNION ALLSELECT 'lead', emailFROM leadsORDER BY email;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Emails labeled by source4 sample rows
| source | |
|---|---|
| lead | asha@example.com |
| customer | asha@example.com |
| customer | kabir@example.com |
| lead | mei@example.com |
Note: The repeated email demonstrates that UNION ALL keeps duplicates; row values are sample data.
Key takeaway: Match columns by position, and put ORDER BY once at the end.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Line up the columns
Make each query return the same columns in the same order, with compatible types. Cast where needed.
SELECT id, email … /SELECT id, email …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
Strengths: Cheapest: just appends rows.
Watch out: Keeps duplicates, so you must be sure that's what you want.
Strengths: Each row appears once.
Watch out: Sorts or hashes the whole result; can be slow on big data.
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?
Knowledge check
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.