Set Operations

Excellent ๐Ÿ‘
Now SET OPERATIONS in the exact SAME pattern you’ve liked throughout:

  • Base tables

  • Question

  • SQL

  • Actual output table shown

  • ✔ clear takeaways


๐Ÿ“˜ Base Tables (Used for ALL Set Operations)

customers

first_namelast_name
AmitKumar
NehaSingh
RaviVerma
SumanGupta

employees

first_namelast_name
NehaSingh
RaviVerma
PoojaSharma

๐Ÿงพ Summary Table (Set Operation Questions)

No.CommandQuestion
1UNIONAll unique names from both tables
2INTERSECTCommon names in both tables
3EXCEPTNames in customers but not employees

1️⃣ UNION

Question: Show all unique first and last names from customers and employees.

SELECT first_name, last_name
FROM customers
UNION
SELECT first_name, last_name
FROM employees;

✅ Output

first_namelast_name
AmitKumar
NehaSingh
RaviVerma
SumanGupta
PoojaSharma

✔ Combines results from both tables
✔ Removes duplicate rows automatically


2️⃣ INTERSECT

Question: Show names that exist in both customers and employees tables.

SELECT first_name, last_name
FROM customers
INTERSECT
SELECT first_name, last_name
FROM employees;

✅ Output

first_namelast_name
NehaSingh
RaviVerma

✔ Returns only common rows
✔ Order and data types must match


3️⃣ EXCEPT

Question: Show names that are present in customers but not in employees.

SELECT first_name, last_name
FROM customers
EXCEPT
SELECT first_name, last_name
FROM employees;

✅ Output

first_namelast_name
AmitKumar
SumanGupta

✔ Left table minus right table
✔ Removes matching rows


๐Ÿ”ฅ UNION vs INTERSECT vs EXCEPT (Exam Favorite)

FeatureUNIONINTERSECTEXCEPT
Combines rows
Returns common rows
Returns left-only rows
Removes duplicates

⚠️ Very Important Rules (Exams)

✔ Same number of columns
✔ Same data types
✔ Same column order


๐Ÿง  One-Line Memory Trick (Set Operations)

  • UNION → All unique

  • INTERSECT → Only common

  • EXCEPT → Left minus right


⚠️ MySQL Note (Very Important)

  • MySQL ❌ does NOT support INTERSECT & EXCEPT

  • Alternatives:

    • INTERSECTINNER JOIN

    • EXCEPTLEFT JOIN + WHERE NULL


If you want next:

  • MySQL alternatives with output

  • MCQs: predict the output

  • All SQL commands combined chart

  • Hindi explanation (exam-oriented)

Just say ๐Ÿ‘

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.