SQL UNION vs UNION ALL: Examples and Differences

Mark Gates
Mark Gates Author & Technology Writer
Published Updated

UNION combines rows from separate SQL queries into one result, and each column position must describe the same kind of value. Default to UNION ALL, which keeps every row, and use UNION only when removing identical rows is part of the requirement.

A join does a different job by placing related columns beside each other. Use explicit column lists, and do not use a growing union to hide a schema problem.

How Do You Write a SQL UNION Query?

Write one SELECT query, add UNION or UNION ALL, then write the next query. Each query must return the same number of columns, with compatible types in matching positions:

SELECT email, created_at, 'customer' AS source
FROM customers

UNION

SELECT email, created_at, 'subscriber' AS source
FROM newsletter_subscribers;

The result has one column set: email, created_at, and source. The first column in one query matches the first column in the other, regardless of their names. The same rule applies to every position.

Make the columns explicit because SELECT * is lazy in a normal query and worse in a union, where one extra column can break the whole thing.

How Does SQL UNION Remove Duplicates?

UNION removes duplicate rows from the final result:

SELECT email
FROM customers

UNION

SELECT email
FROM newsletter_subscribers;

Suppose customers contains Alex and Sam, while newsletter_subscribers contains Sam and Taylor. The expected result has three rows. This order is shown for readability and is not guaranteed without ORDER BY:

email
------------------
alex@example.com
sam@example.com
taylor@example.com

Sam's identical row appears once. Duplicate removal changes the meaning of the result and requires extra work, so use it only when deduplication belongs to the requirement.

When Should You Use UNION ALL?

Use UNION ALL when every selected row should remain in the result, including duplicates:

SELECT email
FROM customers

UNION ALL

SELECT email
FROM newsletter_subscribers;

With the same sample inputs, the expected result keeps both Sam rows:

email
------------------
alex@example.com
sam@example.com
sam@example.com
taylor@example.com

Use UNION ALL when duplicates are meaningful or the inputs cannot overlap. Use UNION when the combined result must contain distinct selected rows.

How Do You Sort a UNION Result?

An ORDER BY at the end sorts the combined result:

SELECT title, published_at
FROM articles

UNION ALL

SELECT title, published_at
FROM archived_articles

ORDER BY published_at DESC
LIMIT 20;

That ORDER BY belongs to the final result, not only to the second query. If each input needs its own limit or sort before combining, put that query in a subquery and make the intent visible:

SELECT id, title, published_at
FROM (
    SELECT id, title, published_at
    FROM articles
    ORDER BY published_at DESC, id DESC
    LIMIT 20
) AS recent_live

UNION ALL

SELECT id, title, published_at
FROM (
    SELECT id, title, published_at
    FROM archived_articles
    ORDER BY published_at DESC, id DESC
    LIMIT 20
) AS recent_archive

ORDER BY published_at DESC, id DESC
LIMIT 20;

That is more typing, but it makes each branch's trimming rule visible before the final merge.

When Should You Combine SQL Results With UNION?

Use SQL UNION or UNION ALL to combine lists with matching columns, such as current and archived orders or contacts from two sources:

  • Current rows plus archived rows.
  • Customers plus newsletter-only contacts.
  • Internal events plus external events.
  • Search hits from two same-shaped sources.
  • Reports that need one list from several tables.

Weak union use cases often sound like schema confusion:

  • Two tables that should be one table with a type column.
  • Repeated tables by month because partitioning felt too formal.
  • A report that glues unrelated facts together because the UI wants one grid.

A union can keep a legacy report running, but repeated branches become difficult to own once the report turns into business logic. When every new record type needs another branch, inspect the schema and reporting model before extending the query.

How Does UNION Differ From a SQL Join?

A SQL join combines related columns into a row; UNION stacks rows from separate queries. Use a join when one row needs data from related tables:

SELECT orders.id, users.email
FROM orders
JOIN users ON users.id = orders.user_id;

Use a union when two queries produce the same column shape and the rows belong in one list:

SELECT title, published_at
FROM articles

UNION ALL

SELECT title, published_at
FROM archived_articles;

If you are trying to put user columns next to order columns, read SQL joins explained. If you are stacking rows from separate sources, a union may be the right tool.

PHP and Prepared Statements

A PHP query containing UNION still needs prepared-statement parameters for user-supplied values. This example uses an existing PDO connection in $pdo:

<?php

$statement = $pdo->prepare(
    "SELECT title, published_at, 'live' AS source
     FROM articles
     WHERE title LIKE :term_live

     UNION ALL

     SELECT title, published_at, 'archive' AS source
     FROM archived_articles
     WHERE title LIKE :term_archive

     ORDER BY published_at DESC
     LIMIT 20"
);

$statement->execute([
    "term_live" => "%" . $query . "%",
    "term_archive" => "%" . $query . "%",
]);

Do not parameterize table names or other SQL identifiers. Prepared-statement parameters represent values, not identifiers or arbitrary SQL fragments. The PHP PDO guide explains binding values safely. If users can choose which tables enter the union, map their choice to a fixed allowlist in PHP before building the query.

Common Pitfalls & Debugging

The Branches Return Different Column Counts

The database rejects the union before returning rows. one branch added or removed a selected column. list every column explicitly and align each position by meaning, not only by type.

Compatible Types Change the Value

Numbers become text or dates lose the expected representation. the engine found a common output type across mismatched branch expressions. cast each branch deliberately and confirm the combined column type in the target database.

A Branch Sort Is Mistaken for Final Order

The displayed rows move between executions. a sort inside one branch was assumed to order the combined result. apply ORDER BY after the final branch, using the output column name or supported position.

Choose UNION ALL Unless You Need Distinct Rows

Reach for UNION ALL when you want to stack compatible rows and keep them all. Reach for UNION when duplicate removal is part of the requirement. Reach for a join when the row needs related data from another table.

And when a union keeps growing new branches, step back to schema design basics before the query becomes the schema nobody meant to design.

Frequently Asked Questions

Can UNION combine more than two SELECT queries?

SQL UNION can combine more than two SELECT queries by placing UNION or UNION ALL between each pair. Every query must return the same number of columns with compatible types in matching positions. Use a subquery when an input needs its own limit or ordering.

Which SELECT defines the column names in a UNION result?

The first SELECT normally supplies a UNION result’s column names. Alias its expressions clearly because aliases in later queries do not rename the final columns. Use those output names in the final ORDER BY.

Can UNION combine results from the same table?

SQL UNION can combine queries against the same table, using different filters, calculations, or labels. A single SELECT with OR or CASE may be simpler when it produces the same result.

When is UNION ALL faster than UNION?

UNION ALL can be faster when duplicate removal is unnecessary because the database can append the branch results without a distinct step. The actual difference depends on row counts and the execution plan, so choose semantics first and measure important queries.

Can you use UNION inside an INSERT statement?

An INSERT ... SELECT statement can use UNION as its source, so several queries can load one table. The selected column count and types must match the target columns.

Can a UNION combine tables from two different databases?

A UNION can combine tables from different databases when the database engine makes both accessible to the query. MySQL can use database-qualified table names on the same server. SQLite can use attached databases; remote databases may require a foreign table, linked server, or another integration.

Can you UNION rows that have no FROM clause?

In PostgreSQL, MySQL, and SQLite, UNION can combine SELECT statements containing literal values without a FROM clause. That can build a small inline list of lookup values.

Sources

  1. [1]
    MySQL UNION Clause
    (dev.mysql.com)
  2. [2]
  3. [3]
    SQLite SELECT
    (sqlite.org)
  4. [4]
    PDO::prepare
    (php.net)