MySQL If Statement

MySQL If Statement

MySQL If Statement if the statement is used in every programming language. If statement basically used when we want to run some statements based on the particular condition.

It returns True when condition satisfied otherwise returns False. MySQL If Statement is different from If Function in MySQL. Basic functionality of if statement works same in  MySQL. We can also use Simple  IF, If-Else, If-Else If .

MySQL If Statement Syntax

If  Statement’s will  execute when condition returns True.

IF condition THEN
   statements;
END IF;

MySQL If Else Statement Syntax

IF condition THEN
   statements;
ELSE
   statements;
END IF;

If  Else if Else Statement Syntax

IF condition THEN
   statements;
ELSE IF
   statements;
ELSE IF
   statements;

******* //We can write n times else if statement

ELSE
   statements;
END IF;

Example

In te below example, We have made one function “TestFunction” which accept integer value as an argument.

DELIMITER //

CREATE FUNCTION TestFunction ( monthly_salary INT )
RETURNS varchar(20)

BEGIN

   DECLARE salary_amount varchar(20);

   IF monthly_salary <= 4000 THEN
      SET salary_amount = 'Low Salary';

   ELSEIF monthly_salary > 4000 AND monthly_salary <= 7000 THEN
      SET salary_amount = 'Avg Salary';

   ELSE
      SET salary_amount = 'High Salary';

   END IF;
  RETURN salary_amount;

END; //

DELIMITER ;

Output :

Learn Create MySQL Table

MySQL if Statement
SELECT MyFirst_Table_id,MyFirst_Table_firstname,TestFunction(5000) FROM myfirst_table;

Leave a comment

Your email address will not be published. Required fields are marked *