MySQL - IF Statement


Advertisements

The IF is a compound MySQL statement which has a single or set of statements and a condition. If the value of the specified condition is TRUE then, the given statement(s) are executed. Each statement may have one of more SQL statements. An empty statement is not allowed in IF.

Syntax

Following is the syntax of the IF statement in MySQL −

IF search_condition THEN statement_list
   [ELSEIF search_condition THEN statement_list] ...
   [ELSE statement_list]
END IF

Where, statement_list is a single or set of statements that are to be executed. And search_condition is the condition of the statement.

Example 1

Following query demonstrates the usage of the IF statement with a procedure −

mysql> Delimiter //
mysql> CREATE procedure loopDemo()
   label:BEGIN
      DECLARE val INT ;
      DECLARE result VARCHAR(255);
      SET val =1;
      SET result = '';
         loop_label: LOOP
         IF val > 10 THEN
            LEAVE loop_label;
         END IF;
         SET result = CONCAT(result,val,',');
         SET val = val + 1;
         ITERATE loop_label;
      END LOOP;
      SELECT result;
   END//

You can call the above procedure as follows −

mysql> call loopDemo;//
+-----------------------+
| result                |
+-----------------------+
| 1,2,3,4,5,6,7,8,9,10, |
+-----------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.07 sec)

Example 2

Following query demonstrates how to use the IF statement with in a function. −

DELIMITER //
CREATE FUNCTION Sample (bonus INT)
   RETURNS INT
   BEGIN
      DECLARE income INT;
      SET income = 0;
      myLabel: LOOP
         SET income = income + bonus;
         IF income < 10000 THEN
            ITERATE myLabel;
         END IF;
         LEAVE myLabel;
      END LOOP myLabel;
   RETURN income;
END; //
Query OK, 0 rows affected (0.41 sec)
mysql> DELIMITER ;

You can call the above created function as shown below −

mysql> SELECT Sample(1000);
+--------------+
| Sample(1000) |
+--------------+
| 10000        |
+--------------+
1 row in set (0.15 sec)
mysql_statements_reference.htm
Advertisements