SQL Set Operators (UNION, INTERSECT, EXCEPT) πΈοΈ¶
Mentor's Note: Set operators are the "Socializers" of SQL. They allow you to take results from Query A and Query B and mash them together based on mathematical rules. Think of Venn Diagrams! π‘
π The Scenario: The Merged Contact List π±¶
Imagine you have two separate lists of email subscribers: one from your Website and one from your Mobile App.
- UNION: "Combine both lists and remove anyone who is on both." (Unique list) π
- UNION ALL: "Combine both lists and keep everyone, even if they are repeated." (Fastest) β‘
- INTERSECT: "Only show people who are on BOTH lists." π€
- EXCEPT / MINUS: "Show people on the Website list who are NOT on the App list." π«
π» 1. The UNION & UNION ALL Operators¶
Used to combine rows from two queries.
-- Scenario: Unique list of cities from both Tables
SELECT city FROM customers
UNION
SELECT city FROM suppliers;
-- Scenario: Total list including duplicates
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;
π» 2. The INTERSECT Operator π€¶
Returns only the common rows that exist in both queries.
-- Scenario: Find cities where we have both a Customer AND a Supplier
SELECT city FROM customers
INTERSECT
SELECT city FROM suppliers;
π» 3. The EXCEPT / MINUS Operator π«¶
Returns rows from the first query that are not present in the second.
π¨ Visual Logic: Venn Diagrams¶
UNION: [ ( A + B ) ] <-- Full Combined Area
INTERSECT: [ ( A β© B ) ] <-- The Overlap Only
EXCEPT: [ ( A ) - B ] <-- Only the "Left" side
β οΈ The "Golden Rules" for Set Operations¶
To use these operators, your two queries must match:
1. Same Number of Columns: Both SELECTs must have 3 columns if the first one does.
2. Compatible Data Types: You can't match a 'Name' (String) with a 'Salary' (Number) in the same position.
3. Order: Only the last query can have an ORDER BY.