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.
- Oracle
- SQL Server / Postgre / MySQL
-- Oracle uses 'MINUS'
SELECT city FROM customers
MINUS
SELECT city FROM suppliers;
-- Standard 'EXCEPT'
SELECT city FROM customers
EXCEPT
SELECT city FROM suppliers;
π¨ 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:
- Same Number of Columns: Both SELECTs must have 3 columns if the first one does.
- Compatible Data Types: You can't match a 'Name' (String) with a 'Salary' (Number) in the same position.
- Order: Only the last query can have an
ORDER BY.