totn MySQL

MySQL: IF-THEN-ELSE Statement

This MySQL tutorial explains how to use the IF-THEN-ELSE statement in MySQL with syntax and examples.

Description

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.

Syntax

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;
ELSEIF
Optional. You would use the ELSEIF condition when you want to execute a set of statements when a second condition (ie: condition2) is TRUE.
ELSE
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.

Note

  • Once a condition is found to be TRUE, the IF-THEN-ELSE statement will execute the corresponding code and not evaluate the conditions any further.
  • If no condition is met, the ELSE portion of the IF-THEN-ELSE statement will be executed.
  • It is important to note that the ELSEIF and ELSE portions are optional.

Example

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.