Tutorial

Set Operators in SQL: UNION, UNION ALL, INTERSECT & EXCEPT Guide

Master set operators in SQL with practical examples of UNION, UNION ALL, INTERSECT, and EXCEPT/MINUS to combine query result sets effectively.

Anuj SainiSep 8, 20268 min read

In relational database management systems and data warehousing, set operators in SQL provide the standard mechanism to aggregate, compare, and reconcile disparate data feeds. Whether you are merging historical archive tables with active transaction logs, verifying ETL reconciliation discrepancies, or filtering shared customers across departments, understanding set operations is an essential analytical superpower.

In this guide, complementing our guides on what is SQL and SQL joins explained with examples, we explore all four set operators in SQL, compare set operations against relational joins, and examine query performance benchmarks.


What are Set Operators in SQL?

Derived from mathematical set theory (Venn diagrams), set operators in SQL operate on two or more relation sets. To successfully execute any set operation, your individual queries must satisfy two strict structural prerequisites:

  1. Identical Column Count: Each SELECT statement in the chain must return the exact same number of columns.
  2. Compatible Data Types: The data type of column 1 in query A must match or be implicitly convertible to column 1 in query B.
sql
-- Valid Set Operation: Both return 2 columns of matching types (INT, VARCHAR)
SELECT employee_id, employee_name FROM domestic_staff
UNION ALL
SELECT contractor_id, contractor_name FROM overseas_contractors;

Column Headers Rule

The column aliases and headers displayed in the final output result are determined entirely by the first SELECT query in the chain. Subsequent query column names are ignored.


Core Set Operators in SQL: Syntax & Examples

Feature / Criteria

1. UNION: Combine Result Sets with Deduplication

The UNION operator appends rows from both queries and automatically eliminates duplicate rows across the combined result:

sql
-- Find all unique customer email addresses across marketing and support systems
SELECT email FROM marketing_leads
UNION
SELECT email FROM support_tickets
ORDER BY email;

If an email exists in both tables, it appears only once in the final result set.

2. UNION ALL: Combine Result Sets Retaining Duplicates

The UNION ALL operator concatenates rows directly without inspecting the records for duplicates. This makes it substantially faster because the database skips expensive in-memory sort or hash operations:

sql
-- Union current active orders and archived historical orders
SELECT order_id, customer_id, order_date, total_amount, 'active' AS source 
FROM current_orders
UNION ALL
SELECT order_id, customer_id, order_date, total_amount, 'archived' AS source 
FROM historical_orders;

Always Default to UNION ALL

Unless business requirements explicitly mandate removing duplicate rows, always prefer UNION ALL over UNION. In large data warehouse queries spanning millions of rows, UNION ALL avoids high-memory sort spills to disk.

3. INTERSECT: Find Overlapping Rows

The INTERSECT operator returns only the rows that appear in both queries. Any row that exists in only one query is omitted:

sql
-- Identify VIP customers who purchased in BOTH 2025 and 2026
SELECT customer_id FROM orders WHERE EXTRACT(YEAR FROM order_date) = 2025
INTERSECT
SELECT customer_id FROM orders WHERE EXTRACT(YEAR FROM order_date) = 2026;

4. EXCEPT / MINUS: Find Asymmetric Differences

The EXCEPT operator (called MINUS in Oracle) returns all unique rows present in the first query that do not appear in the second query:

sql
-- Find customers who signed up in 2026 but have never placed an order
SELECT customer_id FROM customers WHERE registration_year = 2026
EXCEPT
SELECT DISTINCT customer_id FROM orders;

MySQL Workaround for Older Versions

If your MySQL version does not support EXCEPT, simulate the behavior using a LEFT JOIN or NOT EXISTS:

sql
SELECT c.customer_id
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE c.registration_year = 2026 AND o.customer_id IS NULL;

Set Operators vs SQL JOINs: When to Use Which

Engineers frequently ask whether to use a JOIN or a set operator:

Feature / Criteria

Advanced Set Operators in SQL: Multi-Query ETL and Audit Frameworks

Beyond simple row-stacking, senior analytics engineers deploy set operators in sql to construct automated reconciliation frameworks that detect data drift between staging and production tables. Browse our SQL Tutorials hub for more enterprise patterns.

Building a Automated Data Diff Engine with EXCEPT and UNION ALL

When migrating transactional databases to modern cloud warehouses, analysts verify table parity by constructing a two-way differential comparison query:

sql
-- Find rows present in Source but missing in Target
(
    SELECT customer_id, email, status, tier FROM src_customers
    EXCEPT
    SELECT customer_id, email, status, tier FROM tgt_customers
)
UNION ALL
-- Find rows present in Target but missing in Source
(
    SELECT customer_id, email, status, tier FROM tgt_customers
    EXCEPT
    SELECT customer_id, email, status, tier FROM src_customers
);

If the combined query returns zero rows, the two tables are byte-for-byte identical across all checked columns. If discrepancies exist, the exact deviating records are surfaced immediately.

Schema Alignment Rules for Set Operators in SQL

Set operations enforce strict compile-time rules across participating SELECT statements:

  1. Column Count Parity: Each query must return the exact same number of expressions. A query returning 3 columns cannot be unioned with a query returning 4 columns.
  2. Data Type Compatibility: Corresponding columns must have compatible data types. If Query 1 returns a UUID in position 1, Query 2 must return a UUID or an explicitly castable string type.
  3. Column Aliases from the First Query: Column names in the final result set are determined exclusively by the aliases declared in the first SELECT statement:
    sql
    SELECT user_name AS account_identifier FROM active_users
    UNION
    SELECT email FROM archived_users;
    -- Final output column header will be 'account_identifier'
  4. ORDER BY Position: ORDER BY can appear only once, at the very end of the entire compound statement, referencing column names or numeric positions from the initial query.

Practical Real-World Use Cases for Set Operators in SQL

Auditing Data Discrepancies Between Environments

During database migrations or ETL pipeline refactoring, set operators allow you to rapidly verify that two tables are identical:

sql
-- If this query returns 0 rows, both tables match exactly!
(
    SELECT sku, price, stock_quantity FROM legacy_inventory
    EXCEPT
    SELECT sku, price, stock_quantity FROM modern_inventory
)
UNION ALL
(
    SELECT sku, price, stock_quantity FROM modern_inventory
    EXCEPT
    SELECT sku, price, stock_quantity FROM legacy_inventory
);

For more query building blocks, read our SQL cheat sheet and guide to DDL commands in SQL.


Summary Checklist for Set Operators in SQL

  • Ensure all combined queries have the identical number of columns.
  • Verify data types in corresponding column positions are mutually compatible.
  • Prefer UNION ALL over UNION whenever duplicates are impossible or acceptable.
  • Remember that ORDER BY can only appear once at the very end of the final query.
  • Use EXCEPT / MINUS to validate staging data against production tables during ETL runs.

Set Operators in SQL: Real-World Multi-Region Data Aggregation

In multinational corporations, data from regional subsidiaries often lives in separate database instances with identical table structures:

sql
-- Consolidating multi-region revenue into a unified global dataset
SELECT 'North America' AS region, order_id, customer_id, order_total, order_date
FROM na_sales.orders
WHERE order_status = 'Completed'
UNION ALL
SELECT 'Europe' AS region, order_id, customer_id, order_total, order_date
FROM eu_sales.orders
WHERE order_status = 'Completed'
UNION ALL
SELECT 'Asia-Pacific' AS region, order_id, customer_id, order_total, order_date
FROM apac_sales.orders
WHERE order_status = 'Completed';

Using UNION ALL preserves all transactions without spending expensive CPU cycles de-duplicating rows across disjoint geographies. Explore our SQL Tutorials hub for more enterprise SQL architecture.

Level Up Your SQL Analytics & Query Logic

Practice set operators, complex joins, and window functions on real-world datasets with interactive grading.

Start Free SQL Course

Frequently Asked Questions

What are set operators in SQL?

Set operators in SQL are relational operators that combine the result sets of two or more independent SELECT queries into a single unified result. The primary set operators are UNION, UNION ALL, INTERSECT, and EXCEPT (or MINUS).

What is the difference between UNION and UNION ALL?

UNION combines results and performs an automatic deduplication sort to remove identical rows, which incurs a performance cost. UNION ALL combines results directly without deduplicating, preserving all duplicate rows and executing significantly faster.

What are the prerequisite rules for using set operators in SQL?

All SELECT queries connected by set operators must have the exact same number of columns, and corresponding columns must have compatible data types in the same order. Column names in the final output are determined by the first query.

Which SQL databases support EXCEPT vs MINUS?

PostgreSQL, SQLite, and Microsoft SQL Server use the ANSI standard keyword EXCEPT. Oracle Database uses MINUS. MySQL 8.0.31+ supports EXCEPT, whereas earlier MySQL versions simulate it using LEFT JOIN or NOT EXISTS.

How do set operators differ from SQL JOINs?

JOINs combine tables horizontally based on a matching key column, adding more columns to the output. Set operators combine queries vertically, stacking rows on top of each other while maintaining the same column structure.

Anuj Saini

Written by

Anuj SainiFounder & Lead Instructor

Founder at Topfolio with 6+ years in data & analytics across JPMC, Ultrahuman, and high-growth startups. Sat on hiring panels, reviewed 500+ resumes, and writes practical SQL & data guides.