How to use the CASE statement in MySQL

The CASE statement in MySQL is a conditional statement that goes through conditions one by one and returns the value provided for the first satisfying condition.


Syntax

Given below is the syntax for the CASE statement:

svg viewer
  • condition_1, ... condition_k: Conditions that need to be evaluated (in the same order in which they are listed).

  • return_1, ..., return_k: Return values if the respective condition is satisfied. If no condition is satisfied, and there is no ELSE clause, NULL is returned.

Note: A CASE statement must have at least one condition that returns a value. More than one conditions and even the ELSE clause is optional.


Example

Consider the following table, Persons. Given below is a query that demonstrates how to use the CASE statement:

svg viewer

The CASE statement given below (Lines 2-7) has three conditions that check whether the Salary of a person is less than 1800, equal to 1800 or more than 1800. The returned string value is then printed out for each row along with the first and last name of that person (Line 1).

SELECT P.FirstName, P.LastName,
CASE
WHEN P.Salary < 1800 THEN 'Less Than 1800'
WHEN P.Salary = 1800 THEN 'Equal To 1800'
WHEN P.Salary > 1800 THEN 'More Than 1800'
ELSE 'No Salary Data Found'
END
FROM Persons P;
Copyright ©2024 Educative, Inc. All rights reserved