Course contentsShow
← Data Science
Lesson 999 of 2,14526. Advanced SQLFree lesson

UNION: Combining Distinct Results

Learn to combine rows from multiple SELECT statements while automatically removing duplicates.

UNION: Combining Distinct Results

What you'll learn: How to stack results from multiple SELECT statements into one result set while automatically removing duplicates.

The Core Idea

Think of UNION as stacking two or more result tables on top of each other, but with a twist: it automatically removes any duplicate rows. It's like combining two guest lists for a party and crossing out anyone who appears twice—you end up with one clean list of unique attendees.

When you use UNION, SQL takes the rows from the first query, adds the rows from the second query, and filters out any exact duplicates across all columns.

Basic Syntax

SELECT column1, column2 FROM table1
UNION
SELECT column1, column2 FROM table2;

Important Rules

  1. Column Count Must Match: Both queries must return the same number of columns
  2. Compatible Data Types: Corresponding columns must have compatible data types
  3. Column Names: The result uses column names from the first SELECT
  4. Automatic Deduplication: Duplicate rows are removed automatically

Example

SELECT customer_id, customer_name FROM active_customers
UNION
SELECT customer_id, customer_name FROM vip_customers;

This combines both customer lists, but if someone appears in both tables, they'll only show up once in the final result.

When to Use UNION

  • Merging similar data from multiple tables with the same structure
  • Combining results from different time periods or regions
  • Creating reports that consolidate data from multiple sources
  • When you need a distinct, unified view of scattered data

Key Takeaway: UNION vertically combines results from multiple SELECT statements while automatically eliminating duplicate rows, requiring matched column counts and compatible data types.