1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL UNION vs UNION ALL: Differences, Examples and Performance Tested

The difference between them is one word, but choosing wrong can silently give you the wrong total. See both on real data, learn the rules they share, and read what happened when we timed them on a million rows.

8 min read
SQL UNION vs UNION ALL: differences, examples and performance tested

Key takeaways

  • UNION combines results and removes duplicate rows. UNION ALL keeps every row.
  • Deduplicating costs work, so UNION ALL is usually faster to compute.
  • Using UNION before a SUM can silently remove real values and give the wrong answer.
  • Default to UNION ALL, unless you specifically want duplicates removed.

Both operators stack the results of two queries on top of each other, so SQL UNION vs UNION ALL might look like a minor choice. It is not. One extra word changes both your result and how hard the database has to work.

We ran every query here in SQLite 3.50, and the results and timings shown come from those runs. The basic behaviour is standard SQL across major databases. Timings, however, will differ on your own database, data and hardware, so treat ours as an illustration.

The short answer

UNION combines two result sets and returns only distinct rows. UNION ALL combines them and returns everything, including duplicates. That is the whole difference, and the rest of this article is about why it matters.

UNION vs UNION ALL side by side

Aspect UNION UNION ALL
Duplicate rows Removed Kept
Extra work Must find duplicates None
Usual speed Slower Faster
Rows returned Same or fewer All of them
Safe before SUM or COUNT? Often not Yes
Best for Unique lists Merging data, logs, totals

The sample data

Imagine a shop that keeps online and in-store orders in separate tables. Note that Asha has two identical online orders, and one identical order in store.

CREATE TABLE online_orders (customer TEXT, total INT);
CREATE TABLE store_orders (customer TEXT, total INT);

INSERT INTO online_orders VALUES ('Asha',100), ('Ben',200), ('Asha',100);
INSERT INTO store_orders VALUES ('Asha',100), ('Dev',300);

See the difference

SELECT customer, total FROM online_orders
UNION
SELECT customer, total FROM store_orders;

-- Asha | 100
-- Ben  | 200
-- Dev  | 300
SELECT customer, total FROM online_orders
UNION ALL
SELECT customer, total FROM store_orders;

-- Asha | 100
-- Ben  | 200
-- Asha | 100
-- Asha | 100
-- Dev  | 300

Five input rows became three with UNION, and all five stayed with UNION ALL. Two things to notice:

  • UNION removed duplicates from the whole result, including those within the first table. It is not only comparing across tables.
  • A row counts as a duplicate only when every selected column matches.

When you truly want a distinct list, UNION is exactly right. This gives every customer who bought through either channel:

SELECT customer FROM online_orders
UNION
SELECT customer FROM store_orders;

-- Asha
-- Ben
-- Dev

The wrong-total bug

This is the reason the choice really matters. Suppose you want total revenue. The orders above add up to 800. See what each operator gives:

SELECT SUM(total) FROM (
  SELECT total FROM online_orders
  UNION
  SELECT total FROM store_orders
);
-- 600

SELECT SUM(total) FROM (
  SELECT total FROM online_orders
  UNION ALL
  SELECT total FROM store_orders
);
-- 800

The UNION version is wrong by 200. Because we selected only the total column, three separate 100-rupee orders looked like duplicates and collapsed into one. There is no error message, and 600 looks like a perfectly believable number. This type of quiet bug can sit in a finance report for months.

Tip: Two identical-looking rows may be two genuine events. Before you use UNION, ask whether identical rows mean the same fact recorded twice, or two different facts. For sales, payments and log entries, it is usually the second.

Rules both must follow

Both operators have the same requirements:

  1. Each SELECT must return the same number of columns.
  2. Columns are matched by position, not by name, so keep them in the same order.
  3. Data types in each position must be compatible.
  4. Result column names come from the first SELECT.
  5. ORDER BY goes at the very end, and it applies to the whole result.

Breaking the first rule gives an error. Here is the message from SQLite:

SELECT customer, total FROM online_orders
UNION
SELECT customer FROM store_orders;

-- SELECTs to the left and right of UNION do not have
-- the same number of result columns

The second rule is more dangerous, because it can fail without an error. If you swap two columns of the same type, such as first_name and last_name, the query runs and the data comes out wrong. SQLite is also relaxed about types, while databases such as PostgreSQL are stricter and may require an explicit CAST.

Label the source

A very practical trick is to add a constant column showing where each row came from. Because the label differs, rows from different tables can no longer be treated as duplicates of each other.

SELECT customer, total, 'online' AS channel FROM online_orders
UNION ALL
SELECT customer, total, 'store' FROM store_orders
ORDER BY customer, channel;

-- Asha | 100 | online
-- Asha | 100 | online
-- Asha | 100 | store
-- Ben  | 200 | online
-- Dev  | 300 | store

Once your data has a label, you can group it to report sales by channel, using GROUP BY. If you need to combine several steps, wrap the union in a CTE to keep it readable.

Performance: what happened in our test

To remove duplicates, the database has to compare rows, typically by sorting or hashing them. UNION ALL can skip this step. We created two tables with 500,000 rows each, containing random numbers from 0 to 50,000, so there were plenty of duplicates. We ran each query several times and kept the best time.

First, we counted the results, so that the time spent sending rows back to our program did not affect the comparison:

Query, wrapped in COUNT(*) Rows Best time
UNION 50,001 261 ms
UNION ALL 1,000,000 Under 1 ms

The huge gap is partly because SQLite can work out that count without reading every row, so please do not read that as “thousands of times faster”. It does show the core idea, though: UNION had to do real work and UNION ALL did not.

Then we fetched all the rows into Python, and the result flipped:

Query, fetching all rows Rows returned Best time
UNION 50,001 277 ms
UNION ALL 1,000,000 392 ms

Here, UNION ALL took longer because it delivered twenty times as many rows. Deduplication is not what slowed it. Handling a million rows was. So the honest rule is that UNION ALL is cheaper for the database to compute, but the size of the result matters too. Many charts online reduce this to “UNION ALL is always faster”, and our test shows why it is not that simple.

Do not choose based on speed alone, either. Pick the operator that gives the correct answer first, then tune. If a query is slow, read our guide to SQL query optimization.

When to use each

Use UNION ALL when:

  • You are merging data from similar tables, such as monthly partitions.
  • You will calculate totals or counts afterwards.
  • You know the inputs cannot overlap.
  • Duplicates are meaningful, as in logs or audit records.

Use UNION when:

  • You need a unique list, such as every email address across two systems.
  • Overlapping sources contain the same fact more than once.

Treat UNION ALL as the default, and use UNION deliberately. Adding a WHERE clause to each branch, to filter early, helps both.

INTERSECT and EXCEPT

Two related set operators answer different questions. Both follow the same column rules:

SELECT customer FROM online_orders
INTERSECT
SELECT customer FROM store_orders;
-- Asha  (bought in both channels)

SELECT customer FROM online_orders
EXCEPT
SELECT customer FROM store_orders;
-- Ben   (online only)

Oracle has traditionally used MINUS rather than EXCEPT, and support for these operators varies a little by database and version.

UNION vs JOIN

These are often confused, but they combine data in different directions:

Operation Direction Result
UNION Vertical Adds more rows
JOIN Horizontal Adds more columns

Common mistakes

  • Using UNION by habit. It may cost you speed, or remove valid rows.
  • Selecting too few columns. Leaving out an ID makes distinct rows look identical.
  • Mismatching column order. Values can land in the wrong column without any error.
  • Adding ORDER BY to each branch. Sort once, at the end.
  • Using UNION to patch a bad join. If duplicates appear because of a join, fix the join.
  • Assuming result order. Without ORDER BY, row order is not guaranteed for either operator.

Final thoughts

Ask one question each time: are identical rows the same fact, or separate facts? If they are separate, or if overlap is impossible, use UNION ALL. If you need a unique list, use UNION. To check your own reports, search your code for UNION near a SUM or COUNT, and confirm that those totals really are right.

Frequently asked questions

What is the difference between UNION and UNION ALL?

UNION combines two result sets and removes duplicate rows. UNION ALL combines them and keeps every row, including duplicates.

Which is faster, UNION or UNION ALL?

UNION ALL is usually cheaper to compute, because it does not check for duplicates. Returning a far larger result can still take longer overall, as our test showed.

Does UNION remove duplicates within one table?

Yes. It removes duplicates across the entire combined result, including identical rows that all came from the same table.

Do column names have to match in a UNION?

No. Columns are matched by position, and the result uses names from the first SELECT. The column count must match, and the types must be compatible.

Can I use ORDER BY with UNION?

Yes, but place one ORDER BY at the very end of the statement. It sorts the entire combined result rather than a single branch.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →