SQL
CASE WHEN STATEMENT
Pooja Mistry
Mastering CASE WHEN in SQL –
The Ultimate Conditional Logic
Tool!
Ever struggled to apply IF-ELSE
conditions in SQL?
Need to categorize or transform data
dynamically?
Want to ace your next SQL interview?
The CASE WHEN statement is one of the
most powerful and versatile SQL
functions that helps you apply
conditional logic directly inside your
queries. Let’s dive in!
Pooja Mistry
What is CASE WHEN in SQL?
• The CASE WHEN statement works like
an IF-ELSE condition in programming
languages.
• It allows you to evaluate conditions
and return different results based on
those conditions.
Basic Syntax:
CASE
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
ELSE default_result
END
Pooja Mistry
How CASE WHEN in SQL Works:
• Conditions are evaluated from top to
bottom
• The first true condition is returned
• If no conditions match, it returns the
ELSE value (or NULL if ELSE is omitted)
Where Can You Use CASE
WHEN?
• In SELECT Statements (Categorizing data)
• With Aggregation Functions (SUM, COUNT,
etc.)
• In GROUP BY Queries (Conditional grouping)
• For Handling NULL Values
• In ORDER BY (Custom sorting)
• Inside JOINS (Applying conditions across
tables)
Pooja Mistry
Categorizing Data (Labeling Results)
Example:
SELECT Order_ID, Amount,
CASE
WHEN Amount > 1000 THEN 'High'
WHEN Amount BETWEEN 500 AND 1000 THEN
'Medium'
ELSE 'Low'
END AS Sales_Category
FROM Sales;
Pooja Mistry
Using CASE WHEN Inside Aggregate
Functions
Example:
SELECT
SUM(CASE WHEN Amount > 1000 THEN Amount
ELSE 0 END) AS High_Value_Sales,
SUM(CASE WHEN Amount <= 1000 THEN Amount
ELSE 0 END) AS Low_Value_Sales
FROM Sales;
Pooja Mistry
Handling NULL Values (Replacing
NULLs with Default Values)
Example:
SELECT Customer_Name,
CASE
WHEN Address IS NULL THEN 'Unknown Address'
ELSE Address
END AS Updated_Address
FROM Customers;
Pooja Mistry
CASE WHEN in ORDER BY (Custom
Sorting)
Example:
SELECT Employee_Name, Department
FROM Employees
ORDER BY
CASE
WHEN Department = 'HR' THEN 1
WHEN Department = 'IT' THEN 2
ELSE 3
END;
Pooja Mistry
CASE WHEN with GROUP BY
(Conditional Aggregation)
Example:
SELECT
CASE
WHEN Amount > 1000 THEN 'High'
WHEN Amount BETWEEN 500 AND 1000 THEN
'Medium'
ELSE 'Low'
END AS Sales_Category,
COUNT(*) AS Order_Count
FROM Sales
GROUP BY
Sales_Category;
Pooja Mistry
CASE WHEN in JOINS (Applying
Conditions Across Tables)
Example:
SELECT E.Name, D.Department,
CASE
WHEN D.Department IS NULL THEN 'No
Department Assigned'
ELSE D.Department
END AS Department_Status
FROM Employees E
LEFT JOIN Departments D ON E.Dept_ID = D.Dept_ID;
Pooja Mistry