Conditional Expressions

Perfect ๐Ÿ‘
Now Conditional Expressions in the exact SAME format:

  • Base tables

  • Summary table (questions)

  • For EACH topic: Question → SQL → Output → ✔ explanation


๐Ÿ“˜ Base Tables (Used for ALL examples)

orders

order_idtotal_amountdiscounted_amount
10112001000
102700700
103300250

employees

emp_idfirst_namemiddle_nameage
1AmitNULL28
2NehaKumari55
3RaviNULL42

๐Ÿงพ Summary Table (Conditional Questions)

No.ExpressionQuestion
1CASECategorize orders by value
2IF()Classify employees by age
3COALESCE()Show preferred employee name
4NULLIF()Compare two amounts

1️⃣ CASE Statement

Question: Categorize orders as High, Medium, or Low value.

SELECT
order_id,
total_amount,
CASE
  WHEN total_amount > 1000 THEN 'High Value Order'
  WHEN total_amount > 500 THEN 'Medium Value Order'
  ELSE 'Low Value Order'
END AS order_status
FROM orders;

✅ Output

order_idtotal_amountorder_status
1011200High Value Order
102700Medium Value Order
103300Low Value Order

✔ Multiple conditions supported
✔ Works like IF–ELSE ladder


2️⃣ IF() Function

Question: Classify employees as Senior or Junior based on age.

SELECT
first_name,
age,
IF(age > 50, 'Senior', 'Junior') AS employee_category
FROM employees;

✅ Output

first_nameageemployee_category
Amit28Junior
Neha55Senior
Ravi42Junior

✔ Only one condition
✔ Mostly used in MySQL


3️⃣ COALESCE() Function

Question: Show preferred name (first non-NULL value).

SELECT
COALESCE(first_name, middle_name) AS preferred_name
FROM employees;

✅ Output

preferred_name
Amit
Neha
Ravi

✔ Returns first non-NULL value
✔ Very useful for handling NULLs


4️⃣ NULLIF() Function

Question: Return NULL if total_amount equals discounted_amount.

SELECT
order_id,
NULLIF(total_amount, discounted_amount) AS diff_amount
FROM orders;

✅ Output

order_iddiff_amount
1011200
102NULL
103300

✔ Returns NULL when values are equal
✔ Prevents divide-by-zero & comparison issues


๐Ÿ”ฅ CASE vs IF (Exam Favorite)

FeatureCASEIF()
ConditionsMultipleSingle
SQL Standard✅ Yes❌ MySQL-specific
ReadabilityHighMedium

๐Ÿง  One-Line Memory Trick

ExpressionMeaning
CASEIF–ELSE ladder
IF()Single condition
COALESCEFirst non-NULL
NULLIFNULL if equal

⚠️ Exam Traps

  • CASE is portable across DBs

  • IF() may not work in Oracle / SQL Server

  • COALESCE can take multiple values

  • NULLIF(a,b) → returns NULL if a = b


If you want next:

  • CASE + GROUP BY examples

  • Conditional expressions MCQs

  • Hindi explanation for exams

  • All SQL functions cheat-sheet

Just say ๐Ÿ‘

No comments:

Post a Comment

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