🗄️ SQL — Level 3: CASE WHEN, NULL Handling & Conditional Logic
In the previous part, you learned how to summarize data using GROUP BY and aggregate functions.
Now we're going to make SQL more powerful by learning how to create categories, handle missing data, and apply business rules.
These skills are extremely important because real-world datasets are rarely perfect.
You may need to answer questions like:
Which orders are High, Medium, or Low value?
How many customers have missing information?
What should we display when a value is NULL?
How many employees are above their target?
This is where CASE WHEN and NULL-handling functions become essential.
1️⃣ What Is CASE WHEN?
CASE WHEN allows SQL to make decisions.
Think of it as the SQL equivalent of Excel's:
IF()
For example:
CASE
WHEN Sales >= 100000 THEN 'High'
WHEN Sales >= 50000 THEN 'Medium'
ELSE 'Low'
END
SQL evaluates the conditions and returns the appropriate category.
2️⃣ Basic CASE WHEN
Suppose you have:
Order_ID | Sales
1001 | 120,000
1002 | 75,000
1003 | 30,000
You want to classify orders.
SELECT
Order_ID,
Sales,
CASE
WHEN Sales >= 100000 THEN 'High'
WHEN Sales >= 50000 THEN 'Medium'
ELSE 'Low'
END AS Sales_Category
FROM Orders;
Result:
Order_ID | Sales | Sales_Category
1001 | 120,000 | High
1002 | 75,000 | Medium
1003 | 30,000 | Low
3️⃣ Understand the Evaluation Order
SQL evaluates the WHEN conditions from top to bottom.
For example:
CASE
WHEN Sales >= 100000 THEN 'High'
WHEN Sales >= 50000 THEN 'Medium'
ELSE 'Low'
END
If Sales = 120000:
Is it ≥ 100000? ✅
Return High
Stop evaluating the remaining conditions.
That's why the order of conditions matters.
4️⃣ CASE WHEN with Categories
Suppose employees have salaries.
You want:
₹100,000+ → Senior
₹60,000–99,999 → Mid-Level
Below ₹60,000 → Junior
SELECT
Name,
Salary,
CASE
WHEN Salary >= 100000 THEN 'Senior'
WHEN Salary >= 60000 THEN 'Mid-Level'
ELSE 'Junior'
END AS Salary_Level
FROM Employees;
This is a common data transformation technique.
5️⃣ CASE WHEN with Text Conditions
You can also evaluate text.
Suppose:
Department
IT
HR
Finance
Sales
You want to categorize IT and Finance as:
Business-Critical
and everything else as:
Other
SELECT
Name,
Department,
CASE
WHEN Department IN ('IT', 'Finance')
THEN 'Business-Critical'
ELSE 'Other'
END AS Department_Type
FROM Employees;
6️⃣ CASE WHEN with AND
You can combine multiple conditions.
Suppose an employee qualifies for a bonus if:
Department = IT
Salary > ₹80,000
SELECT
Name,
Department,
Salary,
CASE
WHEN Department = 'IT'
AND Salary > 80000
THEN 'Bonus Eligible'
ELSE 'Not Eligible'
END AS Bonus_Status
FROM Employees;
Both conditions must be true.
7️⃣ CASE WHEN with OR
Suppose employees from IT or Finance should receive a particular classification.
SELECT
Name,
Department,
CASE
WHEN Department = 'IT'
OR Department = 'Finance'
THEN 'Priority'
ELSE 'Standard'
END AS Employee_Type
FROM Employees;