Skip to main content

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.

  1. UNION: "Combine both lists and remove anyone who is on both." (Unique list) πŸ’Ž
  2. UNION ALL: "Combine both lists and keep everyone, even if they are repeated." (Fastest) ⚑
  3. INTERSECT: "Only show people who are on BOTH lists." 🀝
  4. 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 uses 'MINUS'
SELECT city FROM customers
MINUS
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:

  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.

πŸ“ˆ Learning Path​

πŸ“ Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
πŸ“ Address
2/66 Faram Street, Rustompura
Surat – 395002, Gujarat, India
πŸ“ž Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition β€” Areas We Serve in Surat

Adajanβ€’Althanβ€’Amroliβ€’Athwaβ€’Athwalinesβ€’Bhagalβ€’Bhatarβ€’Bhestanβ€’Canal Roadβ€’Chowkβ€’Citylightβ€’Dumasβ€’Gaurav Pathβ€’Ghod Dod Roadβ€’Haziraβ€’Jahangirpuraβ€’Kamrejβ€’Kapodraβ€’Katargamβ€’Limbayatβ€’Magdallaβ€’Majura Gateβ€’Mota Varachhaβ€’Nanpuraβ€’New Citylightβ€’Olpadβ€’Palβ€’Pandesaraβ€’Parle Pointβ€’Piplodβ€’Punaβ€’Randerβ€’Ring Roadβ€’Rustampuraβ€’Sachinβ€’Salabatpuraβ€’Sarthanaβ€’Sosyo Circleβ€’Udhnaβ€’Varachhaβ€’Ved Roadβ€’Vesuβ€’VIP Road
πŸ“ž Call SirπŸ’¬ WhatsApp Sir