Mastering MySQL for Data AnalystsLesson 22 of 42
Lesson 22 of 42

Set Operations: UNION & UNION ALL in MySQL

Overview & Learning Objectives

While JOINs combine tables horizontally by adding columns, Set Operations combine result sets vertically by stacking rows. In MySQL, `UNION` merges the results of two or more queries into a single output while executing a deduplication pass. In contrast, `UNION ALL` appends rows directly without sorting, running vastly faster and preserving duplicates. Analysts also learn how to emulate `INTERSECT` and `EXCEPT` in MySQL.

  • Stack query results vertically using `UNION` and `UNION ALL`.
  • Understand the performance advantage of `UNION ALL` over `UNION`.
  • Emulate ANSI `INTERSECT` and `EXCEPT` operations in MySQL using `INNER JOIN` and `LEFT JOIN`.

Industry Standard

Standard: Data warehouse engineers at Uber and Meta mandate `UNION ALL` for merging partitioned monthly tables because data is pre-partitioned and deduplication sorting is redundant.

Real-World Example: ScoopCraft Multi-Channel Marketing Contact List

ScoopCraft marketing consolidates customer mobile numbers from app signups and POS walk-in receipts for an SMS campaign.

OperationLeft RowsRight RowsOutput CountExecution Speed
UNION ALL50,000 app users30,000 store users80,000 total rows0.04 seconds (Fast stream append)
UNION50,000 app users30,000 store users62,000 unique rows0.45 seconds (Sort deduplication pass)

Functions & Syntax Covered in this Chapter

Here is the definition, execution syntax, parameter breakdown, and real-world business example for each function/syntax covered in this chapter:

Feature 1

UNION (Distinct Set Combine)

Definition: Combines the result sets of two or more SELECT queries into a single result set, performing an automatic deduplication sort pass across all rows.

Syntax / Code Pattern:
SELECT phone FROM retail_customers UNION SELECT phone FROM online_customers;
Parameters Breakdown:
  • SELECT queries: Must have identical number of columns with compatible data types in the same order.
Real-World Example (Unique Marketing Audience List):
Problem / Scenario: Combine phone numbers from physical store walk-ins and mobile app users without duplicates.
SQL Query / Expression: SELECT phone FROM store_cust UNION SELECT phone FROM app_cust
Result: Unified unique phone list with zero duplicate entries
Why it works: MySQL stacks both result sets and executes an internal temporary table deduplication.
Feature 2

UNION ALL (Fast Set Combine)

Definition: Combines multiple SELECT queries preserving all duplicate rows without performing costly deduplication sorting.

Syntax / Code Pattern:
SELECT order_id, amount FROM jan_sales UNION ALL SELECT order_id, amount FROM feb_sales;
Parameters Breakdown:
  • SELECT queries: Must match column count and compatible types.
Real-World Example (Consolidated Transaction Audit Log):
Problem / Scenario: Combine Q1 and Q2 transaction records for accounting ledger totals.
SQL Query / Expression: SELECT * FROM q1_orders UNION ALL SELECT * FROM q2_orders
Result: All 100,000 rows retained with original duplicate records intact
Why it works: Appends data streams directly, running 5x-10x faster than UNION by bypassing sort deduplication.

Common Mistakes & Limitations

  • Using `UNION` when `UNION ALL` was intended, accidentally losing valid duplicate business transactions.
  • Attempting to use `INTERSECT` or `EXCEPT` in older MySQL versions (MySQL 8.0.31+ added INTERSECT/EXCEPT, but older versions require JOIN emulation).

Keyboard Shortcuts (MySQL Workbench)

ActionWindowsMac
Execute QueryCtrl + EnterCmd + Enter

Pro Tips & Modern Best Practices

  • In a `UNION` query, column names in the final result set are determined by the first `SELECT` statement.
  • Only a single `ORDER BY` clause is permitted at the very end of the entire combined union query.