Skip to content

Set Operations: UNION, INTERSECT and EXCEPT

Beginning of the lesson

Set Operations: UNION, INTERSECT and EXCEPT

Stack, overlap and subtract whole result sets - not columns, but entire rows

Big Idea: A set operation takes the rows produced by two SELECT queries and combines them vertically. A JOIN glues tables side by side to make wider rows; a set operation stacks result sets on top of each other to make one longer list. UNION merges them, INTERSECT keeps only rows present in both, and EXCEPT keeps rows in the first that are missing from the second.
By the end you will be able to:
  • combine two result sets with UNION and know when to reach for UNION ALL instead,
  • find rows common to two queries with INTERSECT,
  • subtract one result set from another with EXCEPT,
  • satisfy the column compatibility rules that every set operation demands,
  • reproduce INTERSECT and EXCEPT on older MySQL that lacks them (before 8.0.31).

1. Our example database

Every query below runs against two small tables. A company keeps a list of its employees and, separately, a list of its customers. Both records happen to store a person's name and their city.

CREATE TABLE employees (
    emp_id  INT PRIMARY KEY,
    name    VARCHAR(50),
    city    VARCHAR(50)
);

CREATE TABLE customers (
    cust_id INT PRIMARY KEY,
    name    VARCHAR(50),
    city    VARCHAR(50)
);

INSERT INTO employees (emp_id, name, city) VALUES
    (1, 'Alice', 'London'),
    (2, 'Bob',   'Paris'),
    (3, 'Carol', 'London'),
    (4, 'David', 'Berlin');

INSERT INTO customers (cust_id, name, city) VALUES
    (101, 'Emma',  'Paris'),
    (102, 'Frank', 'London'),
    (103, 'Grace', 'Paris'),
    (104, 'Alice', 'Madrid');

Keep these eight rows in mind. Notice the cities: employees live in London, Paris and Berlin; customers live in Paris, London and Madrid. Those overlaps and differences are exactly what set operations let us describe.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers