This tutorial explains how to use the IF-THEN-ELSE statement in MySQL with syntax and examples.
In MySQL, the IF-THEN-ELSE statement is used to execute code when a condition is TRUE, or execute different code if the condition evaluates to FALSE.
The syntax for the IF-THEN-ELSE statement in MySQL is:
IF condition1 THEN
{...statements to execute when condition1 is TRUE...}
[ ELSEIF condition2 THEN
{...statements to execute when condition1 is FALSE and condition2 is TRUE...} ]
[ ELSE
{...statements to execute when both condition1 and condition2 are FALSE...} ]
END IF;
Optional. You would use the ELSEIF condition when you want to execute a set of statements when a second condition (ie: condition2) is TRUE.
Optional. You would use the ELSE condition when you want to execute a set of statements when none of the IF or ELSEIF conditions evaluated to TRUE.
The following is example using the IF-THEN-ELSE statement in a MySQL function:
DELIMITER //
CREATE FUNCTION IncomeLevel ( monthly_value INT )
RETURNS varchar(20)
BEGIN
DECLARE income_level varchar(20);
IF monthly_value = 4000 THEN
SET income_level = 'Low Income';
ELSEIF monthly_value > 4000 AND monthly_value = 7000 THEN
SET income_level = 'Avg Income';
ELSE
SET income_level = 'High Income';
END IF;
RETURN income_level;
END; //
DELIMITER ;
In this IF-THEN-ELSE statement example, we've created a function called IncomeLevel. It has one parameter called monthly_value and it returns a varchar(20). The function will return the income level based on the monthly_value.