🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

UNION, INTERSECT, EXCEPT

SQL JoinsSet OperationsđŸŸĸ Free Lesson
SQL Joins

UNION, INTERSECT, EXCEPT

Merge, find commonalities, and subtract result sets from multiple queries.

  • UNION — combines rows from two queries, optionally removing duplicates
  • INTERSECT — returns only rows present in both result sets
  • EXCEPT — returns rows from the first set that are absent in the second Set theory brought to your data.

What Are Set Operations?

UNIONABAâˆĒBAll rows combinedINTERSECTABA∊BOnly common rowsEXCEPTABA−BOnly in A, not B
SELECT columns FROM table_a
UNION
SELECT columns FROM table_b;

UNION

UNION vs UNION ALL

OperationDuplicatesPerformanceUse When
UNIONRemovedSlower (sorting/dedup)You need unique results
UNION ALLKeptFaster (no dedup)Duplicates are acceptable
-- UNION: removes duplicate rows
SELECT city FROM customers
UNION
SELECT city FROM suppliers;

-- UNION ALL: keeps all rows including duplicates
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;

Basic UNION Example

-- Combine employee and customer names into one list
SELECT first_name, last_name, 'Employee' AS type
FROM employees
UNION
SELECT first_name, last_name, 'Customer' AS type
FROM customers
ORDER BY last_name, first_name;

UNION with Multiple Queries

-- Quarterly sales summary
SELECT 'Q1' AS quarter, SUM(sales) AS total_sales FROM sales WHERE quarter = 1
UNION
SELECT 'Q2', SUM(sales) FROM sales WHERE quarter = 2
UNION
SELECT 'Q3', SUM(sales) FROM sales WHERE quarter = 3
UNION
SELECT 'Q4', SUM(sales) FROM sales WHERE quarter = 4;

INTERSECT

Returns only the rows that appear in both result sets.

-- Find customers who are also employees
SELECT first_name, last_name, email
FROM customers
INTERSECT
SELECT first_name, last_name, email
FROM employees;

INTERSECT with Multiple Columns

-- Find employees whose current department and salary match a historical record
SELECT department_id, salary
FROM employees
INTERSECT
SELECT department_id, salary
FROM job_history;
ScenarioINTERSECT Use
Common customersCustomers present in both 2022 and 2023 orders
Shared skillsEmployees who have both certifications
Overlapping dataRecords matching across two data sources
-- Find products that were ordered in both January and February
SELECT product_id FROM order_items
INNER JOIN orders ON order_items.order_id = orders.order_id
WHERE MONTH(order_date) = 1
INTERSECT
SELECT product_id FROM order_items
INNER JOIN orders ON order_items.order_id = orders.order_id
WHERE MONTH(order_date) = 2;

EXCEPT (or MINUS)

Returns rows from the first query that do not appear in the second.

-- Customers who have never placed an order
SELECT customer_id, first_name, last_name
FROM customers
EXCEPT
SELECT DISTINCT c.customer_id, c.first_name, c.last_name
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id;

EXCEPT vs NOT IN vs NOT EXISTS

-- Using EXCEPT
SELECT customer_id FROM customers
EXCEPT
SELECT customer_id FROM orders;

-- Using NOT IN
SELECT customer_id FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders);

-- Using NOT EXISTS (often best performance)
SELECT c.customer_id FROM customers c
WHERE NOT EXISTS (
    SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
MethodProsCons
EXCEPTClean, set-based syntaxNot supported everywhere
NOT INSimple to writeIssues with NULLs
NOT EXISTSBest performance, NULL-safeSlightly more verbose

Rules for Set Operations

RuleDescription
Same column countAll queries must return the same number of columns
Compatible typesCorresponding columns must have compatible data types
Column order mattersColumns are matched by position, not name
ORDER BY at the endOnly one ORDER BY, applied to the final result
Aliases from first queryColumn names come from the first SELECT
-- Valid: same number of compatible columns
SELECT first_name, last_name, salary
FROM employees
UNION
SELECT first_name, last_name, NULL AS salary
FROM customers;

-- Invalid: different column counts (error)
SELECT first_name, last_name
FROM employees
UNION
SELECT first_name, last_name, email
FROM customers;

Combining Set Operations

-- Combine UNION and EXCEPT in a single query
SELECT first_name, last_name, 'Employee' AS type FROM employees
UNION ALL
SELECT first_name, last_name, 'Customer' AS type FROM customers
EXCEPT
SELECT first_name, last_name, 'Inactive' AS type FROM inactive_users
ORDER BY last_name, first_name;

Performance Considerations

FactorRecommendation
UNION ALL vs UNIONPrefer UNION ALL when duplicates are fine — avoids expensive dedup
Index usageSet operations may bypass indexes — consider temp tables
Sorting costUNION requires sorting for duplicate removal
Large datasetsUse temporary tables for complex multi-step set operations
Execution planAlways EXPLAIN to check if indexes are used
-- When UNION ALL is sufficient, always use it
SELECT customer_id FROM orders_2022
UNION ALL
SELECT customer_id FROM orders_2023;

-- Only use UNION if you truly need deduplication
SELECT customer_id FROM orders_2022
UNION
SELECT customer_id FROM orders_2023;

Practice Exercises

Exercise 1: Combine employee and customer names into a single deduplicated list.

-- Solution
SELECT first_name, last_name, 'Employee' AS type
FROM employees
UNION
SELECT first_name, last_name, 'Customer' AS type
FROM customers
ORDER BY last_name, first_name;

Exercise 2: Find products that were ordered in both 2022 and 2023.

-- Solution
SELECT product_id FROM order_items
INNER JOIN orders ON order_items.order_id = orders.order_id
WHERE YEAR(order_date) = 2022
INTERSECT
SELECT product_id FROM order_items
INNER JOIN orders ON order_items.order_id = orders.order_id
WHERE YEAR(order_date) = 2023;

Exercise 3: Find customers who registered in 2023 but have never placed an order.

-- Solution
SELECT customer_id, first_name, last_name
FROM customers
WHERE YEAR(registration_date) = 2023
EXCEPT
SELECT DISTINCT c.customer_id, c.first_name, c.last_name
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id;

See Also


Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement