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:
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.
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.
The following is example using the IF-THEN-ELSE statement in a MySQL function:
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.