This lesson on EXCEPT, INTERSECT, UNION — For Diffs and Dedup is hands-on and example-driven. Master SQL set operations—UNION, UNION ALL, INTERSECT, and EXCEPT—to combine, deduplicate, and find row-level differences across queries. You will learn the structural prerequisites for set queries and how ordering alters asymmetric difference operations.
What You'll Be Able To Do
- Combine disparate row sets while removing duplicates using UNION
- Preserve duplicate records across datasets using UNION ALL
- Identify common rows across multiple datasets using INTERSECT
- Isolate asymmetric differences between datasets using directional EXCEPT queries
- Verify column count and data type compatibility before executing set operations
Detailed Concept Walkthrough
1. Set Operation Structural Prerequisites
Set operators process entire result sets vertically rather than joining them horizontally. Both input queries must share compatible structural schemas to allow row alignment.
- Syntax Rule: Every query participating in a set operation must select the exact same number of columns in identical positional order. SQL aligns data by column position rather than column names.
- Type Compatibility: Corresponding positional columns between queries must have identical or implicitly convertible data types. If types mismatch, the database engine raises a type mismatch error during execution.
- Best Practice: Explicitly alias columns in the first SELECT statement, as the top query's column names dictate the output schema headers for the combined result set.
-- Both queries must match in column count and data types
SELECT id1, name1 FROM u1
UNION
SELECT id1, name1 FROM u2;
-- Output column headers will inherit from u1 (id1, name1)
Key Takeaway: Set operations require matching column counts and compatible data types across all participating SELECT statements.
2. Combining Data with UNION vs UNION ALL
UNION and UNION ALL merge rows vertically from two datasets, differing strictly in how they handle duplicate rows across the combined output.
- Mechanism: UNION merges records from both datasets and runs a deduplication step to retain only distinct rows. UNION ALL concatenates the datasets directly, retaining all occurrences of duplicate rows.
- Under the Hood: UNION performs an implicit distinct sort or hash operation to strip duplicates, incurring higher computational overhead. UNION ALL skips this filtering phase, executing significantly faster.
- Best Practice: Default to UNION ALL when rows are guaranteed to be unique or when preserving duplicate occurrences is required for business logic.
-- UNION: Combines and removes duplicates (e.g., rows 4 and 5 appear once)
SELECT id1, name1 FROM u1
UNION
SELECT id1, name1 FROM u2;
-- UNION ALL: Combines without deduplicating (e.g., rows 4 and 5 appear twice)
SELECT id1, name1 FROM u1
UNION ALL
SELECT id1, name1 FROM u2;
Key Takeaway: UNION ALL appends results without overhead, while UNION forces a distinct sort to eliminate duplicates.
3. Finding Overlaps with INTERSECT
INTERSECT isolates rows that are present in both input datasets simultaneously, acting as a strict mathematical intersection.
- Mechanism: INTERSECT evaluates complete rows between the left and right queries and outputs only the rows that exist in both sets.
- Deduplication: Similar to UNION, INTERSECT automatically removes duplicate occurrences from the intersection output, returning each matching row once.
- Use Case: Use INTERSECT when you need to verify common records between two versions of a table or validate shared entities across staging and production tables.
-- INTERSECT: Returns only rows that exist in both u1 and u2 (rows 4 and 5)
SELECT id1, name1 FROM u1
INTERSECT
SELECT id1, name1 FROM u2;
Key Takeaway: INTERSECT returns unique rows common to both participating queries.
4. Finding Differences with Directional EXCEPT
EXCEPT implements set difference (A - B) by taking all unique rows from the first query and subtracting any rows found in the second query.
- Execution Flow: The database takes the distinct rows from the first dataset and removes every record that appears anywhere in the second dataset.
- Asymmetry Rule: EXCEPT is non-commutative; running
u1 EXCEPT u2computes (u1 - u2), whereasu2 EXCEPT u1computes (u2 - u1). The two queries yield completely different result sets. - Under the Hood: EXCEPT deduplicates rows from the primary dataset before outputting rows that have no match in the secondary dataset.
-- u1 - u2: Returns rows unique to u1 (rows 1, 2, 3), removing overlap (4, 5)
SELECT id1, name1 FROM u1
EXCEPT
SELECT id1, name1 FROM u2;
-- u2 - u1: Returns rows unique to u2 (rows 6, 7, 8), removing overlap (4, 5)
SELECT id1, name1 FROM u2
EXCEPT
SELECT id1, name1 FROM u1;
Key Takeaway: EXCEPT outputs rows unique to the left dataset, making query ordering critical to the final output.
Topics Covered in EXCEPT, INTERSECT, UNION — For Diffs and Dedup
- Set Operation Overview (0:00 - 0:45) — Introduction to sample tables and structural requirements for SQL set operations.
- UNION Demonstration (0:46 - 1:20) — Executing UNION to combine two datasets while removing overlapping duplicate records.
- UNION ALL Execution (1:21 - 1:40) — Running UNION ALL to demonstrate full dataset concatenation with duplicate rows preserved.
- INTERSECT Operation (1:41 - 2:05) — Using INTERSECT to isolate rows that exist concurrently in both tables.
- EXCEPT (A - B) (2:06 - 2:40) — Demonstrating set subtraction from u1 to u2 to extract unique left-table rows.
- EXCEPT (B - A) (2:41 - 3:16) — Inverting the EXCEPT query order to extract rows unique to the right table.
SQL Cheat Sheet
-
UNION— Combines result sets and eliminates all duplicate rowsSELECT id1, name1 FROM u1 UNION SELECT id1, name1 FROM u2; -
UNION ALL— Combines result sets while retaining all duplicate rowsSELECT id1, name1 FROM u1 UNION ALL SELECT id1, name1 FROM u2; -
INTERSECT— Returns distinct rows shared across both query resultsSELECT id1, name1 FROM u1 INTERSECT SELECT id1, name1 FROM u2; -
EXCEPT (A - B)— Returns distinct rows in left query not in rightSELECT id1, name1 FROM u1 EXCEPT SELECT id1, name1 FROM u2; -
EXCEPT (B - A)— Returns distinct rows in right query not in leftSELECT id1, name1 FROM u2 EXCEPT SELECT id1, name1 FROM u1;
Comparison Table
| Operator | Duplicates Handled | Order Dependent (Commutative) |
|---|---|---|
| UNION | Removes duplicates | No (Commutative) |
| UNION ALL | Preserves duplicates | No (Commutative) |
| INTERSECT | Removes duplicates | No (Commutative) |
| EXCEPT | Removes duplicates | Yes (Non-commutative) |
Common Pitfalls
- Mistake: Expecting EXCEPT to work symmetrically regardless of query order. Avoid: Position the baseline dataset first and the subtracted dataset second.
- Mistake: Using UNION when duplicates are already impossible or acceptable. Avoid: Use UNION ALL to prevent expensive unnecessary distinct sorting operations.
- Mistake: Combining queries with different column counts or incompatible datatypes. Avoid: Explicitly verify matching column counts and compatible data types positional alignment.
FAQs
- Why does EXCEPT return different rows when changing table order? EXCEPT computes set difference (A - B). Inverting the order computes (B - A), isolating records unique to table B instead of table A.
- Does INTERSECT preserve duplicate matching rows? No, INTERSECT returns only distinct rows that exist across both datasets, automatically stripping duplicate occurrences.
- What happens if column names differ between the two SELECT queries? The query executes normally as long as the positional datatypes match; the final output column headers inherit names from the first SELECT query.