The IF statements in MYSQL executes a block of code depending on the condition inside the IF statement, whether is true or false. The condition inside IF statement can be formed by combining literals, variables, operators, and functions. Syntax for IF statements are given below:

IF condition THEN statements

   ELSEIF condition THEN statements ??

   ELSE statements

END IF

The IF statements can have THEN, ELSE, ELSEIF clauses and it ends with END IF. If the condition evaluates to true, the statements within THEN are executed; whether if the condition is false, the program flow goes to ELSEIF clause. If none of the conditions matches the program flow goes to ELSE clause. When there are complex expressions based on multiple values, IF statements are used.

The example below shows the implementation of IF ELSE statements. The marks are retrieved from database. Depending on the range of the marks the result of the candidate 'Reshma' is set.

Example

The IF ELSE statement in stored procedure example:

DELIMITER //

CREATE PROCEDURE getResults(IN marks INT, OUT result VARCHAR(50))

BEGIN

   DECLARE total INT DEFAULT 0;

   SELECT marks INTO total FROM tblResults WHERE name='Reshma';

   IF total > 85 THEN

      SET result="DISTINCTION";

   ELSEIF  (total < 85 AND total >60) THEN

      SET result="FIRST_CLASS";

   ELSEIF  (total < 60 AND total >35) THEN

      SET result="SECOND_CLASS";

   ELSE

      SET result="FAIL";

   END IF;

END //

DELIMITER ;