MySQL – IF Statement
In MySQL, the IF statement is used to implement basic conditional constructs. In response to a certain condition, it allows us to execute a set of SQL statements. This function returns one of three values: True, False, or NULL.
You can use this statement in three ways: IF-THEN, IF-THEN-ELSE, IF-THEN-ELSEIF-ELSE, and END-IF. Let us examine each of these statements in more detail.
Based on certain conditions or expressions, this statement executes a set of SQL queries. Following is the syntax of the IF-THEN statement:
IF condition THEN statements; END IF;
Using the above syntax, we need to specify a condition for executing the code. When the statement evaluates to true, the statement between IF-THEN and END-IF will be executed. Alternatively, it will execute the statement following the END-IF.
This statement can be used if we wish to execute other statements if the condition specified in the IF block does not evaluate to true. The following is the syntax of an IF-THEN-ELSE statement:
IF condition THEN statements; ELSE else-statements; END IF;
The syntax above specifies a condition for executing the code. The statement will be executed between IF-THEN and ELSE if it evaluates to true. Otherwise, it will execute the statement following the ELSE and END-IF clauses.
Using this statement, we can execute a statement based on multiple conditions. Below is the syntax for the IF-THEN-ELSE statement:
IF condition THEN statements; ELSEIF elseif-condition THEN elseif-statements; ... ELSE else-statements; END IF;
If the condition is met, the IF-THEN branch will be executed. Alternatively, elseif-condition will be evaluated. If the elseif-condition becomes true, the elseif-statement will be executed. In the event that this condition is also false, the next elseif condition will be evaluated. The statement of the ELSE branch will be executed if any of the conditions in the IF and ELSE-IF do not become true.