Or is not supported with CASE Statement in SQL Server
In SQL, CASE statements direct usage of OR is a no-go. Opt for multiple WHEN clauses or use IN for a list of values instead. Consider this:
Alternatively, leverage IN for compact syntax:
These workarounds reflect the SQL's CASE statement's versatility.
Using 'IN' operator
For value checks against a single column, the IN
operator is your Swiss Army knife. Here you go:
Default values using 'ELSE'
Kick in the 'Plan Busing an
ELSE` clause when no conditions match. Because SQL also believes in "If all else fails, try, try again":
Conditional sorting
CASE
in the ORDER BY
brings custom sorting to your fingertips. Here's a quick peek:
Conditional aggregation
CASE
even joins you in the HAVING
clause to filter grouped data:
Working with Boolean logic
Although direct support for OR
is missing, you can freely weave in Boolean logic within WHEN
clauses. Look, no hands, AND
and OR
:
Performance enhancements
Give prominence to the most probable conditions first to enhance query performance:
Data type considerations
Ensure data types of WHEN
clause results are either a match or are implicitly convertible:
Was this article helpful?