MySQL CASE statement is a flow control feature that allows us to build conditions in a query, such as a SELECT or WHERE clause. We have two CASE statement syntax
CASE val WHEN compare_val1 THEN result1 WHEN compare_val2 THEN result2 . . . Else result END
In the first syntax, if val is equal to compare_val1, the CASE statement returns result1. If val equals compare_val2, the CASE statement returns result2, and so on.
If val does not match any compare_val, the CASE statement returns the result specified in the ELSE clause.
mysql> Select CASE 100 -> WHEN 100 THEN 'It is matched' -> WHEN 200 THEN 'It is not matched' -> ELSE 'No use of this Number' -> END as 'Matching the Number'; +---------------------+ | Matching the Number | +---------------------+ | It is matched | +---------------------+ 1 row in set (0.06 sec)
CASE WHEN condition_1 THEN result1 WHEN condition_2 THEN result2 . . . Else result END
In the second syntax, the CASE statement returns result 1, result 2, etc.. If the condition is true. If all conditions are false, the CASE statement returns the result specified in the ELSE clause.
mysql> Select CASE -> WHEN (100 = 100) THEN 'It is Matched' -> WHEN (200 = 100) Then 'It is Not Matched' -> Else 'No use of Number' -> END as 'Matching the Number'; +---------------------+ | Matching the Number | +---------------------+ | It is Matched | +---------------------+ 1 row in set (0.00 sec)
The above is the detailed content of How does the MYSQL control flow function CASE work?. For more information, please follow other related articles on the PHP Chinese website!