Academic Block

SQL UNION Get Certified

Learn how to combine the results of two or more SELECT statements into a single result set using the UNION operator.

What is the UNION Operator?

The UNION operator stacks the results of multiple SELECT statements on top of each other. By default it removes duplicate rows so that every combination of values appears only once.

Each SELECT must return the same number of columns, and the corresponding columns must have compatible data types. The column names of the final result come from the first SELECT.

Basic UNION Syntax

The simplest form combines two result sets that have identical structure.

What this code does: Combines the morning and evening student lists into one result. Because the student IDs are different, no rows are removed. The final list is sorted by student_id and contains 6 rows.

WITH morning_students(student_id, student_name) AS (
  VALUES
    (1, 'Aarav'),
    (2, 'Meera'),
    (3, 'Kabir')
),
evening_students(student_id, student_name) AS (
  VALUES
    (4, 'Riya'),
    (5, 'Dev'),
    (6, 'Tara')
)
SELECT student_id, student_name
FROM morning_students
UNION
SELECT student_id, student_name
FROM evening_students
ORDER BY student_id;

UNION Removes Duplicate Rows

One of the defining features of UNION is that it automatically eliminates identical rows.

What this code does: Both tables contain the course “SQL”. After the UNION only one copy of “SQL” remains. The final result contains the unique courses: CSS, HTML, Java, Python, SQL.

WITH online_courses(course_name) AS (
  VALUES
    ('SQL'),
    ('Python'),
    ('HTML')
),
classroom_courses(course_name) AS (
  VALUES
    ('SQL'),
    ('Java'),
    ('CSS')
)
SELECT course_name
FROM online_courses
UNION
SELECT course_name
FROM classroom_courses
ORDER BY course_name;

UNION ALL – Keep Every Row

UNION ALL performs the same stacking operation but does not remove duplicates. Use it when you need every row, including repeats, or when you know there are no duplicates and want better performance.

What this code does: Both stores sell Mouse and Monitor. With UNION ALL those products appear twice. The result contains 6 rows instead of the 4 unique products that UNION would return.

WITH store_a(product_name) AS (
  VALUES
    ('Keyboard'),
    ('Mouse'),
    ('Monitor')
),
store_b(product_name) AS (
  VALUES
    ('Mouse'),
    ('Monitor'),
    ('Webcam')
)
SELECT product_name
FROM store_a
UNION ALL
SELECT product_name
FROM store_b
ORDER BY product_name;

UNION from Completely Different Tables

The tables do not have to be related. As long as the selected columns are compatible, UNION can combine them.

What this code does: Produces a single list of people and their cities drawn from both the customers table and the suppliers table. The result contains 4 rows.

WITH customers(person_name, city) AS (
  VALUES
    ('Nisha', 'Delhi'),
    ('Rohan', 'Pune')
),
suppliers(person_name, city) AS (
  VALUES
    ('Karan', 'Mumbai'),
    ('Tanya', 'Jaipur')
)
SELECT person_name, city
FROM customers
UNION
SELECT person_name, city
FROM suppliers
ORDER BY person_name;

UNION with Independent WHERE Clauses

Each SELECT can have its own filtering conditions. The filters are applied before the results are combined.

What this code does: Keeps only the high-value orders (≥ 1000) from both the north and south regions, then merges them. The final list is sorted by amount descending and contains 3 rows.

WITH north_orders(order_id, customer_name, amount) AS (
  VALUES
    (101, 'Aditi', 1200),
    (102, 'Vikram', 450),
    (103, 'Neha', 1800)
),
south_orders(order_id, customer_name, amount) AS (
  VALUES
    (201, 'Arjun', 900),
    (202, 'Pooja', 2200),
    (203, 'Mohan', 700)
)
SELECT order_id, customer_name, amount
FROM north_orders
WHERE amount >= 1000
UNION
SELECT order_id, customer_name, amount
FROM south_orders
WHERE amount >= 1000
ORDER BY amount DESC;

UNION with Calculated Columns and Labels

You can add extra calculated columns or constant labels so that the combined result remains informative.

What this code does: Physical sales use a quantity column while digital sales use downloads. Both are renamed to “units” and a constant sale_type label is added so the two kinds of data can be stacked cleanly. The result is sorted by units descending.

WITH physical_sales(product, quantity) AS (
  VALUES
    ('Notebook', 25),
    ('Planner', 18)
),
digital_sales(product, downloads) AS (
  VALUES
    ('Ebook', 40),
    ('Template', 30)
)
SELECT
  product,
  quantity AS units,
  'Physical' AS sale_type
FROM physical_sales
UNION
SELECT
  product,
  downloads AS units,
  'Digital' AS sale_type
FROM digital_sales
ORDER BY units DESC;

UNION with Three (or More) SELECT Statements

You can chain as many SELECT statements as you need. Each additional UNION simply adds another result set.

What this code does: Combines products sold in Delhi, Mumbai and Pune. “Laptop” appears in both Delhi and Pune, so UNION keeps only one copy. The final unique list contains 5 products.

WITH delhi_products(product_name) AS (
  VALUES
    ('Laptop'),
    ('Keyboard')
),
mumbai_products(product_name) AS (
  VALUES
    ('Monitor'),
    ('Mouse')
),
pune_products(product_name) AS (
  VALUES
    ('Webcam'),
    ('Laptop')
)
SELECT product_name FROM delhi_products
UNION
SELECT product_name FROM mumbai_products
UNION
SELECT product_name FROM pune_products
ORDER BY product_name;

Column Aliases Come from the First SELECT

The names that appear in the final result are taken from the first SELECT. Later SELECTs do not need to repeat the aliases.

What this code does: The first SELECT defines the output column names employee_name and team. The second SELECT simply supplies matching values. The combined list of four employees is sorted by name.

WITH employees_2025(name, department) AS (
  VALUES
    ('Ishita', 'Design'),
    ('Rahul', 'Finance')
),
employees_2026(name, department) AS (
  VALUES
    ('Mira', 'Engineering'),
    ('Dev', 'Marketing')
)
SELECT
  name AS employee_name,
  department AS team
FROM employees_2025
UNION
SELECT
  name,
  department
FROM employees_2026
ORDER BY employee_name;

ORDER BY Must Appear at the End

When you want the combined result sorted, place a single ORDER BY clause after the last SELECT.

What this code does: Merges the scores from two teams and sorts the final four rows by score from highest to lowest.

WITH first_team(member_name, score) AS (
  VALUES
    ('Aman', 75),
    ('Riya', 92)
),
second_team(member_name, score) AS (
  VALUES
    ('Kabir', 84),
    ('Tina', 68)
)
SELECT member_name, score
FROM first_team
UNION
SELECT member_name, score
FROM second_team
ORDER BY score DESC;

UNION vs UNION ALL

Feature
UNION
UNION ALL
Combines results
Yes
Yes
Removes duplicates
Yes
No
Keeps every row
No
Yes
Typical use
Unique combined list
Preserve all rows / better performance

Rules for Using UNION

  • Every SELECT must return the same number of columns.
  • Corresponding columns must have compatible data types.
  • Column names of the final result come from the first SELECT.
  • UNION removes duplicate rows; UNION ALL keeps them.
  • Place ORDER BY only once, at the very end of the complete query.
  • Each individual SELECT may have its own WHERE, GROUP BY, etc.

Common Uses of UNION

  • Combining records from tables that have the same structure (different years, regions, stores…).
  • Creating a single master list from several departmental or location-based tables.
  • Merging historical and current data into one result set.
  • Producing a unified report from multiple independent sources.
  • Quickly consolidating similar data without writing complex joins.

Best Practices

  • Prefer UNION when you need a distinct list of values.
  • Prefer UNION ALL when duplicates are acceptable or when you know the sets are already unique (faster).
  • Keep the column order and data types consistent across every SELECT.
  • Give meaningful aliases in the first SELECT so the final result is easy to read.
  • Always put the ORDER BY clause after the last SELECT.
  • When the query becomes complex, use parentheses to make the structure clear.

The UNION operator stacks the results of multiple SELECT statements into one result set and removes duplicates by default. Use UNION ALL when you want to keep every row. Click Test My Code on any example to run it live, or Code Explanation to walk through the query block by block.

Ctrl + Enter to run code in the editor Esc to close the editor

🧪 Test Your SQL Code

Edit the SQL code on the left and click “Run Code” to see the result on the right.

📝 SQL Code
👁️ Preview (query result)

Click “Run Code” to see the result here.