UNION / UNION ALL – Stacking Results in SQL

UNION / UNION ALL – Stacking Results in SQL
(because sometimes, you need to combine two lists into one)

Quick Syntax

SELECT column1, column2
FROM table1

UNION -- or UNION ALL

SELECT column1, column2
FROM table2;

This tells SQL:
“Run both queries and combine their results. Use UNION to remove duplicates, or UNION ALL to keep everything.”

Context: Suppose You Have Two Tables of Sales

Let’s say you manage sales from two different stores, and each store keeps its own sales records in separate tables.

🛒 Table: store_a_sales

customeramount
Alice100
Bob150
Carol200

🛍️ Table: store_b_sales

customeramount
Alice100
Dave300
Emma180

Suppose You Need To…

…generate a single combined list of all sales from both stores.

Here’s how you’d do it.

Using UNION – Combine & Remove Duplicates

SELECT customer, amount
FROM store_a_sales

UNION

SELECT customer, amount
FROM store_b_sales;

Result:

customeramount
Alice100
Bob150
Carol200
Dave300
Emma180

Notice:
Alice appears only once, even though she exists in both tables. That’s because UNION removes duplicates by default.

Using UNION ALL – Combine & Keep Everything

SELECT customer, amount
FROM store_a_sales

UNION ALL

SELECT customer, amount
FROM store_b_sales;

Result:

customeramount
Alice100
Bob150
Carol200
Alice100
Dave300
Emma180

Here, Alice shows up twice — once from each table. UNION ALL doesn’t remove duplicates.

Let’s Compare

Feature UNION UNION ALL
Duplicates Removed Kept as-is
Speed Slower (filters dups) Faster (no filtering)
Use case Clean, unique list Full raw data (including repeats)

Important Rules

  • Both SELECT queries must have the same number of columns
  • Columns must be in the same order and have compatible data types
  • Use ORDER BY only after the last query:
SELECT ...
UNION
SELECT ...
ORDER BY column_name;

Recap

  • Use UNION when you want no duplicates
  • Use UNION ALL when you want everything, even if it’s repeated
  • Great for combining results from different tables or queries
  • Just remember: same number of columns, same structure

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top