Say I have to following:
Select OrderID =
Case OrderID
When 1 Then 'Customer1'
When 2 Then 'Customer2'
When 3 Then 'Customer2'
Else 'Unknown Customer'
End
From OrdersPlaced
Is it possible to add an or and do something along the lines of:
Select OrderID =
Case OrderID
When 1 Then 'Customer1'
When 2 Or 3 Then 'Customer2'
Else 'Unknown Customer'
End
From OrdersPlaced
In this format, we evaluate one expression against multiple values. In a simple case statement, it evaluates conditions one by one. Once the condition and expression are matched, it returns the expression mentioned in THEN clause. We have following syntax for a case statement in SQL with a simple expression ...
The syntax of the SQL CASE expression is: CASE [expression] WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 ... WHEN condition_n THEN result_n ELSE result END case_name The CASE statement can be written in a few ways, so let’s take a look at these parameters. The parameters or components of the CASE SQL statement are:
case_name (optional): This value indicates what the column should be referred to as when displayed on the screen or from within a subquery. It’s also called the column alias. There are actually two ways to use an SQL CASE statement, which are referred to as a “simple case expression” or a “searched case expression”.
The CASE statement returns the result_1, result_2, or result_3 if the expression matches the corresponding expression in the WHEN clause. If the expression does not match any expression in the WHEN clause, it returns the esle_result in the ELSE clause. The ELSE clause is optional.
There are two forms of CASE
expression, 'searched' and 'simple'. You can't use an OR
with a 'simple' CASE
expression, but you can with the 'searched' form:
Case
When OrderID = 1 Then 'Customer1'
When OrderID = 2 Or
OrderID = 3 Then 'Customer2'
Else 'Unknown Customer'
End
Or even
Case
When OrderID = 1 Then 'Customer1'
When OrderID IN (2, 3) Then 'Customer2'
Else 'Unknown Customer'
End
You can use alternative form of CASE
Select OrderID =
Case
When OrderID = 1 Then 'Customer1'
When OrderID = 2 Or OrderID = 3 Then 'Customer2'
Else 'Unknown Customer'
End
From OrdersPlaced
CASE
expression has two kinds of syntax - the simple (i.e. one that you are showing), and the searched, with multiple logical conditions. If you would like to use an OR
, you need the second kind:
Select OrderID =
Case
When OrderID =1 Then 'Customer1'
When OrderID =2 Or OrderID =3 Then 'Customer2'
Else 'Unknown Customer'
End
From OrdersPlaced
Here is the description from the documentation:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With