MySQL IF Statement
Summary: in 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.
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:
- Optional. You would use the ELSEIF condition when you want to execute a set of statements when a second condition (ie: condition2) is TRUE.
- 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.
- 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.
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.