Oracle Set Operators πΈοΈ
Mentor's Note: Set operators are like "Result Math". Instead of joining tables side-by-side, we take two complete query results and stack them, overlap them, or subtract one from the other. π‘
π The Scenario: The App Merger π±β
Your company has two separate apps: One for the Web and one for Mobile.
- UNION: Get a list of ALL unique emails from both apps.
- INTERSECT: Find users who use BOTH apps.
- MINUS: Find users who use the Web app but have NOT downloaded the Mobile app.
π» 1. UNION & UNION ALL (The Stacker)β
UNION: Combines results and removes duplicates.UNION ALL: Combines results and keeps duplicates (Faster!).
SELECT email FROM web_users
UNION
SELECT email FROM mobile_users;
π» 2. INTERSECT (The Overlap) π€β
Returns only rows that exist in both query results.
SELECT city FROM customers
INTERSECT
SELECT city FROM suppliers;
π» 3. MINUS (The Subtractor) βοΈβ
Returns rows from the first query that are not present in the second.
SELECT product_id FROM inventory
MINUS
SELECT product_id FROM sales; -- "What hasn't sold?"
ποΈ Architect's Note: Performance & Rules π‘οΈβ
- The "Union All" Rule: Always use
UNION ALLinstead ofUNIONif you know there are no duplicates.UNIONforces an expensive "Sort Unique" operation. - Column Rules:
- Both queries must have the same number of columns.
- The data types must be compatible.
- Headers are taken from the first query.