Home > Database > Mysql Tutorial > How does the MYSQL control flow function CASE work?

How does the MYSQL control flow function CASE work?

王林
Release: 2023-09-06 17:17:02
forward
1152 people have browsed it

How does the MYSQL control flow function CASE work?

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

Syntax-1

CASE val
WHEN compare_val1 THEN result1
WHEN compare_val2 THEN result2
.
.
.
Else result
END
Copy after login

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.

Example

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)
Copy after login

Syntax 2

CASE
WHEN condition_1 THEN result1
WHEN condition_2 THEN result2
.
.
.
Else result
END
Copy after login

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.

Example

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)
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template