How to use multiple condition checking in SQL using Case When Then Else End?

In SQL, you can use the CASE WHEN THEN ELSE END structure to make multiple condition judgments. The syntax is as follows:

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ...
    ELSE result
END

The conditions such as condition1 and condition2 are expression conditions, while the results such as result1 and result2 are the corresponding return values for each condition. If condition1 is met, return result1; if condition2 is met, return result2; and so on. If none of the conditions are met, return the result.

Here is an example:

SELECT column1,
       column2,
       CASE
           WHEN column3 = 'A' THEN 'Option A'
           WHEN column3 = 'B' THEN 'Option B'
           ELSE 'Other'
       END AS option
FROM your_table;

In the given example, a condition is evaluated based on the value of column3, and the corresponding option is returned to the option column. If the value of column3 is ‘A’, ‘Option A’ is returned. If the value of column3 is ‘B’, ‘Option B’ is returned. If the value of column3 does not satisfy any condition, ‘Other’ is returned.

bannerAds