This tutorial explains how to use the CASE statement in MySQL with syntax and examples.
In MySQL, the CASE statement has the functionality of an IF-THEN-ELSE statement and has 2 syntaxes that we will explore.
The syntax for the CASE statement in MySQL is:
OR
The value that you are comparing to the list of values. (ie: value_1, value_2, ... value_n).
Evaluated in the order listed. Once a value matches expression, the CASE statement will execute the corresponding statements and not evaluate any further.
Evaluated in the order listed. Once a condition is found to be true, the CASE statement will execute the corresponding statements and not evaluate the conditions any further.
Let's look at an example that shows how to use the CASE statement in MySQL. First, we'll look at the first syntax for the CASE statement. For example:
In this CASE statement example, we have used the first syntax for the CASE statement. In this example, if monthly_value is equal to 4000, then income_level will be set to 'Low Income'. If monthly_value is equal to 5000, then income_level will be set to 'Avg Income'. Otherwise, income_level will be set to 'High Income'.
Let's look at how to use the CASE statement with the second syntax.
In this CASE example, we are using the second syntax for the CASE statement. In this example, if monthly_value is less than or equal to 4000, then income_level will be set to 'Low Income'. If monthly_value is greater than 4000 and less than or equal to 7000, then income_level will be set to 'Avg Income'. Otherwise, income level will be set to 'High Income'.