What is the usage of CASE WHEN in SQL?
In SQL, CASE WHEN is a conditional expression used to return different values based on conditions.
The typical format of grammar is:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END
Conditions such as condition1 and condition2 are expression conditions that can be any expression that can return a boolean value, and results such as result1 and result2 are the outputs returned when the corresponding conditions are met.
When executing a CASE WHEN statement, it evaluates each condition one by one. If a condition is met, it returns the corresponding result and does not evaluate any further conditions. If none of the conditions are met, it returns the result specified after ELSE. If there is no ELSE clause, it returns NULL.
Some examples of when to use the CASE WHEN statement include:
- Performing a condition check on a column and returning different values.
- Performing multiple condition checks on a column to return different outcomes.
- Create derived columns in the query result set.
- Sort the result set based on conditions in the ORDER BY clause.