Rana Maninder Singh
Lesson 7 of 11SQL & DBMS (MySQL)

Set Operators

Lesson opener

In one line: UNION, UNION ALL, INTERSECT, EXCEPT.

Why it matters: Two separate exports merged by hand in Excel duplicate effort and miss rows - stacking queries gives one combined list.

Before this lesson: Dates

Before you start

ResourceLink
PreviousDates
NextSub-queries


What you will learn

UNION, UNION ALL, INTERSECT, EXCEPT.

UNION ALL

[Stack customer ids from two sources]

WHY: Two separate exports merged by hand in Excel duplicate effort and miss rows — stacking queries gives one combined list.

WHEN: You want one sample list of ids that appear as customers and as buyers, tagged by source.

SELECT customer_id AS id, 'customer' AS src FROM customers
UNION ALL
SELECT customer_id AS id, 'buyer' AS src FROM sales
LIMIT 20;

Breaking it down:

Use this when: You're combining two similar-shaped result sets into one table for analysis.


UNION vs UNION ALL

OperatorDuplicates
UNIONRemoved
UNION ALLKept (faster)

INTERSECT / EXCEPT (MySQL 8+)

[Customers who also bought]

WHY: Manual Venn diagrams on two id lists in a spreadsheet break at scale — INTERSECT finds the overlap in the database.

WHEN: You need the exact list of customer ids that appear in both customers and sales.

-- customers who appear in sales
SELECT customer_id FROM customers
INTERSECT
SELECT DISTINCT customer_id FROM sales;

Breaking it down:

Use this when: You want "in both lists" without a join — handy for data-quality checks.


Essential commands

Command / actionWhat it does
UNIONCombine queries; remove duplicate rows.
UNION ALLCombine queries; keep duplicates.
INTERSECTRows appearing in both queries.
EXCEPTRows in first query not in second.

Practice

Before each query, name the three SQL beats — Source → Pattern → Result (SQL translation of Input → Logic → Output — see sql2). For set operators, Source is two compatible SELECTs; Result shape is the stacked or overlapped id list.

Do this now:

  1. UNION ALL stacking customer and buyer ids (worked model below).
  2. One INTERSECT (customers who also appear in sales).
  3. One EXCEPT (or UNION without ALL — know duplicate behavior).
  4. Save 07_sets.sql.

Example framing for task 1:

-- Source: customers.customer_id + sales.customer_id (same column shape)
-- Pattern: UNION ALL (stack; keep duplicates)
-- Result: combined id list tagged by src (sample of 20)

SELECT customer_id AS id, 'customer' AS src FROM customers
UNION ALL
SELECT customer_id AS id, 'buyer' AS src FROM sales
LIMIT 20;

Framing prompts for the rest (fill these blanks in your .sql comments before writing each query):

  1. Source: ___

Pattern: ___

Result: ___

  1. Source: ___

Pattern: ___

Result: ___

Checklist

  • [ ] UNION ALL runs
  • [ ] I know duplicate behavior
  • [ ] Saved script