Home
CASE expressions should end with ELSE clauses
Description
The CASE expression rule states that all CASE expressions should end with an ELSE clause. This clause is used to provide a default value when none of the conditions in the CASE expression are met. This ensures that the CASE expression will always return a value, even if none of the conditions are met. It also helps to make the code more readable and maintainable by making it clear what the default value should be.
Key Benefits
- Ensures consistency : CASE expressions should end with ELSE clauses to ensure that all possible values are accounted for and handled consistently.
- Eliminates errors : By including an ELSE clause, you can eliminate errors that may result from unhandled values.
- Improves readability : An ELSE clause makes it easier to read and understand the logic of the CASE expression.
Non-compliant Code Example
SELECT
carName,
price,
CASE --Non compliant code (Case ends without else clause)
WHEN price > 0 AND price < 500000
THEN 'Low Model'
WHEN price >= 500000 AND price < 1200000
THEN 'Hatchback Model'
WHEN price >= 1200000 AND price < 1500000
THEN 'Sedan Model'
END car_group
FROM
cars
Compliant Code Example
SELECT
carName,
price,
CASE --Compliant code (Case ends with else clause)
WHEN price > 0 AND price < 500000
THEN 'Low Model'
WHEN price >= 500000 AND price < 1200000
THEN 'Hatchback Model'
WHEN price >= 1200000 AND price < 1500000
THEN 'Sedan Model'
ELSE
'Premium Model'
END car_group
FROM
cars