SQL Tutorial SQL Advanced SQL Database SQL References

MySQL CASE() Function



Like the IF statement, The MySQL CASE() function checks conditions and returns a value. It starts with checking the first condition and keep on checking conditions until it finds the condition true (like an IF-THEN-ELSE statement). Once the condition is found to be true, it stops checking the further conditions and returns the value. If no condition is found to be true, then it returns the value in the ELSE clause. If the ELSE clause is not defined, it returns NULL.

Syntax

The syntax for using CASE statement is given below:

CASE  
   WHEN Condition1 THEN Value1
   WHEN Condition2 THEN Value2
   WHEN Condition3 THEN Value3
   ... 
   ELSE Value
END

Example:

Consider a database table called Employee with the following records:

EmpIDNameCityAgeSalary
1JohnLondon253000
2MarryNew York242750
3JoParis272800
4KimAmsterdam303100
5RameshNew Delhi283000
6HuangBeijing282800

  • To fetch Name and Salary data of the employees categorized by salary (using CASE statement) present in the Employee table , the following SQL code can be used:

    SELECT Name, City, Salary, 
    CASE
      WHEN Salary < 2800 THEN 'Salary is less than 2800.'
      WHEN Salary > 2800 THEN 'Salary is greater than 2800.'
      WHEN Salary = 2800 THEN 'Salary is 2800.'
      ELSE 'Salary Data missing.'
    END AS SalaryinCategory 
    FROM Employee;
    

    This will produce the result as shown below:

    NameCitySalarySalaryinCategory
    JohnLondon3000Salary is greater than 2800.
    MarryNew York2750Salary is less than 2800.
    JoParis2800Salary is 2800.
    KimAmsterdam3100Salary is greater than 2800.
    RameshNew Delhi3000Salary is greater than 2800.
    HuangBeijing2800Salary is 2800.
  • Consider the example below where the CASE statement is used to order by result based on given condition.

    SELECT * FROM Employee 
    ORDER BY
    (CASE
      WHEN Age <= 27 THEN Age
      ELSE City
    END);
    

    This result of the following code will be:

    EmpIDNameCityAgeSalary
    2MarryNew York242750
    1JohnLondon253000
    3JoParis272800
    4KimAmsterdam303100
    6HuangBeijing282800
    5RameshNew Delhi283000

❮ MySQL Functions

5