How can MySQL utilize the CASE statement in a query?

In MySQL, you can use the CASE statement in a query to evaluate conditions and return different values. The syntax is as follows:

SELECT 
    CASE
        WHEN condition1 THEN value1
        WHEN condition2 THEN value2
        ELSE defaultValue
    END AS aliasName
FROM tableName;

Here is an example: Let’s say there is a table called “students” with fields id, name, and score. We want to query the grade level of each student.

SELECT 
    name,
    score,
    CASE
        WHEN score >= 90 THEN '优秀'
        WHEN score >= 80 THEN '良好'
        WHEN score >= 60 THEN '及格'
        ELSE '不及格'
    END AS grade
FROM students;

With the query above, it is possible to determine the grade level of each student based on their scores. The CASE statement is a commonly used statement for flexible conditional judgment based on different conditions.

bannerAds