MySQL IF Statement – Tutorialpath

MySQL IF Statement

Summaryin this tutorial, you will learn how to use MySQL IF statement to execute a block of SQL code based on conditions.

In MySQL, 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: MySQL IF ELSE statement
MySQL If Else Statement
MySQL If Else Statement

If the expression evaluates to TRUE , then the statements will be executed, otherwise, the control is passed to the next statement following the END IF.

The following flowchart demonstrates the IF statement:

 

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 example how to use the IF-ELSEIF-ELSE statement. The GetCustomerLevel()  stored procedure accepts two parameters customer number and customer level.

The following flowchart demonstrates the logic of determining customer level.

In this tutorial, you have learned how to use MySQL IF statement to execute a block of SQL code based on conditions.

Leave a Reply

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