← 30 Days of SQL
Day 14 / 30Conditional Logic

CASE WHEN

CASE WHEN is SQL's if-else. Used for bucketing, conditional aggregation, pivoting, and data transformation — appears in almost every real analytics query.

1
Easy

Classify employees as High, Mid, or Low earner based on salary.

SQL Answer
SELECT name, salary,
  CASE
    WHEN salary > 80000 THEN 'High'
    WHEN salary > 40000 THEN 'Mid'
    ELSE 'Low'
  END AS salary_band
FROM employees;
💡

CASE WHEN evaluates conditions top to bottom and returns the first match. ELSE handles any row that doesn't match earlier conditions. Without ELSE, unmatched rows return NULL.

2
Medium

Count employees in each salary band.

SQL Answer
SELECT
  SUM(CASE WHEN salary > 80000 THEN 1 ELSE 0 END) AS high,
  SUM(CASE WHEN salary BETWEEN 40000 AND 80000 THEN 1 ELSE 0 END) AS mid,
  SUM(CASE WHEN salary < 40000 THEN 1 ELSE 0 END) AS low
FROM employees;
💡

Conditional aggregation using CASE inside SUM. Returns one row with three columns instead of three rows — a pivot-style output used in MIS reporting.

3
Medium

Calculate total revenue split by weekday vs weekend orders.

SQL Answer
SELECT
  SUM(CASE WHEN DAYOFWEEK(order_date) IN (1,7) THEN amount ELSE 0 END) AS weekend_rev,
  SUM(CASE WHEN DAYOFWEEK(order_date) NOT IN (1,7) THEN amount ELSE 0 END) AS weekday_rev
FROM orders;
💡

DAYOFWEEK returns 1=Sunday, 7=Saturday in MySQL. Conditional aggregation is the standard way to pivot/split data without multiple queries.

4
Easy

Assign a discount based on order amount: 10% if >5000, 5% if >2000, else 0.

SQL Answer
SELECT order_id, amount,
  CASE
    WHEN amount > 5000 THEN amount * 0.10
    WHEN amount > 2000 THEN amount * 0.05
    ELSE 0
  END AS discount
FROM orders;
💡

CASE WHEN works in any part of SELECT. Conditions are checked in order — since amount > 5000 is checked first, those rows won't also match amount > 2000.

5
Medium

Update a column conditionally (without actually UPDATE — using CASE in SELECT).

SQL Answer
SELECT name,
  CASE
    WHEN department = 'Sales' THEN 'Customer Facing'
    WHEN department IN ('IT', 'Engineering') THEN 'Tech'
    ELSE 'Support'
  END AS dept_category
FROM employees;
💡

CASE WHEN lets you reclassify or relabel values on the fly without changing the underlying data — useful for reporting where business needs different groupings than the data stores.

EVIKA ACADEMY · SQL FOR DATA ANALYTICS

Want to master SQL with live practice?

Join our SQL for Data Analytics course — live classes in Noida and online across India.

Book Free Demo Class →
← PREVIOUSDay 13: Running Totals and Moving AveragesNEXT →Day 15: String Functions
Best Data Analytics Course in Noida Delhi NCR | EVIKA ACADEMY