What is the method of using the “case when” statement?
CASE WHEN is a type of conditional expression used in SQL queries to return different values based on certain conditions.
The basic syntax is as follows:
CASE WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END
- Conditions 1, 2, … are the conditions that need to be checked. If any of the conditions are met, then return the corresponding result.
- The results to be returned when conditions are met are result1, result2, and so on.
- The ELSE clause is optional and is used to specify the default result to return when none of the conditions are met.
The CASE WHEN statement can be nested and can include multiple conditions and multiple results.
For example, the following example will return different bonus percentages based on different levels of sales.
SELECT sales_amount,
CASE WHEN sales_amount > 100000 THEN 'High'
WHEN sales_amount > 50000 THEN 'Medium'
ELSE 'Low'
END AS bonus_level
FROM sales;
The above query will categorize the bonus level of each sale as “High”, “Medium”, or “Low” based on the sales amount.