MariaDB: IF-THEN-ELSE Statement
This MariaDB tutorial explains how to use the IF-THEN-ELSE statement in MariaDB with syntax and examples.
Description
In MariaDB, 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 MariaDB 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 MariaDB function:
DELIMITER // CREATE FUNCTION PageCount ( value INT ) RETURNS varchar(10) DETERMINISTIC BEGIN DECLARE level varchar(20); IF value < 500 THEN SET level = 'Low'; ELSEIF value >= 500 AND value <= 4000 THEN SET level = 'Medium'; ELSE SET level = 'High'; END IF; RETURN level; END; // DELIMITER ;
In this IF-THEN-ELSE statement example, we've created a function called PageCount. It has one parameter called value and it returns a varchar(10). The function will return the level based on the value.
Advertisements