CASE statement in SQL

CASE statement in SQL, The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By and Group By clause, The CASE statement goes through conditions and returns a value when the first condition is  IF-THEN-ELSE statement. So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause. A CASE statement can return only one valueCASE by definition only returns a single value.

CASE Syntax

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN condition3 THEN result3
    WHEN conditionN THEN resultN
    ELSE result
END

Example

SELECT CName, City, Country
FROM Customer
ORDER BY
(CASE
    WHEN City IS NULL THEN Country
    ELSE City
END)

 

2020-05-11