CASE Statements โ Adding Business Logic to SQL ๐ง
In the previous parts, you learned how to:
โข Retrieve data with SELECT
โข Filter data with WHERE
โข Sort results with ORDER BY
โข Summarize data with aggregate functions
โข Group data with GROUP BY
Now it's time to learn how to make SQL think in business categories.
For example:
โข Is this customer High Value, Medium Value, or Low Value?
โข Is this employee's salary High, Medium, or Low?
โข Is this order Small, Medium, or Large?
That's what the CASE expression helps you do.
1๏ธโฃ What is CASE?
CASE allows you to create conditional logic inside SQL.
It's similar to:
โข IF condition
โข THEN result
โข ELSE result
Basic Syntax
SELECT
column_name,
CASE
WHEN condition THEN result
WHEN condition THEN result
ELSE result
END AS new_column
FROM table_name;
2๏ธโฃ Simple CASE Example
Suppose we have employee salaries.
We want to classify employees based on salary.
SELECT
employee_name,
salary,
CASE
WHEN salary >= 1000000 THEN 'High'
WHEN salary >= 600000 THEN 'Medium'
ELSE 'Low'
END AS salary_category
FROM employees;
Result:
employee_name | salary | salary_category
Rahul | 1200000 | High
Priya | 850000 | Medium
Amit | 500000 | Low
3๏ธโฃ How CASE Works
SQL checks conditions from top to bottom.
For:
CASE
WHEN salary >= 1000000 THEN 'High'
WHEN salary >= 600000 THEN 'Medium'
ELSE 'Low'
END
SQL effectively asks:
โข Is salary >= 1,000,000? YES โ High
โข NO โ Is salary >= 600,000? YES โ Medium
โข NO โ Low
Once a matching WHEN condition is found, SQL returns that result.
4๏ธโฃ Order of WHEN Conditions Matters
Consider:
CASE
WHEN salary >= 600000 THEN 'Medium'
WHEN salary >= 1000000 THEN 'High'
ELSE 'Low'
END
This is problematic.
Why?
Someone earning โน12 lakh satisfies:
โข salary >= 600000 first.
So SQL labels them:
โข Medium instead of High
Better:
CASE
WHEN salary >= 1000000 THEN 'High'
WHEN salary >= 600000 THEN 'Medium'
ELSE 'Low'
END
Rule:
โข Put more specific or higher-priority conditions before broader conditions.
5๏ธโฃ CASE With Text Conditions
You can also classify based on text.
Example:
SELECT
employee_name,
department,
CASE
WHEN department = 'IT' THEN 'Technology'
WHEN department = 'Finance' THEN 'Corporate'
WHEN department = 'HR' THEN 'Corporate'
ELSE 'Other'
END AS department_group
FROM employees;
6๏ธโฃ CASE With Multiple Conditions
You can use AND and OR inside WHEN.
Example:
SELECT
customer_name,
city,
customer_segment,
CASE
WHEN customer_segment = 'Premium'
AND city = 'Mumbai'
THEN 'Premium Mumbai'
WHEN customer_segment = 'Premium'
THEN 'Other Premium'
ELSE 'Standard'
END AS customer_group
FROM customers;
7๏ธโฃ CASE With IN
You can combine CASE with IN.
SELECT
customer_name,
city,
CASE
WHEN city IN ('Mumbai', 'Pune', 'Nashik')
THEN 'Maharashtra'
WHEN city IN ('Delhi', 'Noida', 'Gurgaon')
THEN 'NCR'
ELSE 'Other'
END AS region
FROM customers;
This is useful for creating business regions.
8๏ธโฃ CASE With BETWEEN
Example: