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.
Given below is the syntax for the
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
NULL is returned.
CASEstatement must have at least one condition that returns a value. More than one conditions and even the
ELSEclause is optional.
Consider the following table,
Persons. Given below is a query that demonstrates how to use 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;
View all Courses