mySQL if statement

the mysql if statement allows you to execute a set of sql statement based on a certain condition or value of an expression. an expression can return three value false true or null.

MySQL If Statement syntax :

          if  if_expression   then   commands

                                   [elseif  elseif_expression   then  commands]
                                        
                                   [else   commands]
                                        
          end if;

if the if_expression evaluates to true the commands in the if branch will execute.if it evaluates to false, mysql will check the elseif_expression and execute the commands in elseif branch if the elseif_expression evaluates to true.

In the MySQL the if statement no expression evaluates to true, the commands in the else branch will execute.


MySQL If Statement example :-

 
delimiter $$

                create    procedure  getlevel(
                              
                in       u_customernumber  int(10),
                
                out    u_customerlevel     varchar(10))                
 
       begin
                             
                declare   creditlim  double;
                                                   
                               select    creditlimit  into  creditlim
                                                   
                               from       customers
                                                   
                               where     customernumber = u_customernumber;
                                                   
                      if  creditlim  > 50000   then
                                            
                          set  u_customerlevel  = 'platinum' ;
                                              
                      elseif  (creditlim <= 50000  and  creditlim >= 10000)  then
                                             
                          set  u_customerlevel  = 'gold' ;
                                                                 
                      elseif  creditlim < 10000  then
                                            
                          set  u_customerlevel  = 'silver' ;
                                                                 
                      end if;
                                           
                      end$$

in the above example we use the if elseif and else statement to check customer credit limit against multiple values.

the below flow chart that demonstrates the logic of determining customer level