This tutorial explains how to use the MySQL CASE function with syntax and examples.
The MySQL CASE function has the functionality of an IF-THEN-ELSE statement by allowing you to evaluate conditions and return a value when the first condition is met.
The syntax for the CASE function in MySQL is:
Optional. It is the value that you are comparing to the list of conditions. (ie: condition_1, condition_2, ... condition_n)
Evaluated in the order listed. Once a condition is found to be true, the CASE function will return the result and not evaluate the conditions any further.
The value returned once a condition is found to be true.
The CASE function can be used in the following versions of MySQL:
You could use the CASE function in a SQL statement where the expression is included.
In this CASE function example, the expression is quantity whose value would be compared to each of the conditions until one is met. Then the corresponding value would be returned by the CASE function.
You could use the CASE function in a SQL statement where the expression is omitted.
In this CASE function example, an expression has not been included so each condition is individually evaluated and can be completely different and unique. When a condition is met, the corresponding value would be returned.