The article contains information about MYSQL IF Statement, ELSEIF Statement and ELSE STATEMENT used to direct the command flow by condition in the MySQL VTY system.
MySQL IF() Function
We can use two if statements: MySQL if function and if statement.
MySQL if function is used in SQL commands. Similar to the ternary operator statement in programming languages.
1 |
IF(Condition, True, False) |
If the condition written to the first parameter of the MySQL IF function is true, it runs the TRUE parameter, and if it is false, it runs the FALSE parameter.
Using MySQL IF function;
1 |
SELECT IF(5 > 6, "5 is bigger", "6 is bigger") AS result; |
1 |
SELECT *, IF( product_price> 30, "Expensive", "Inexpensive") AS result FROM Products; |
SQL functions can also be used within the MySQL IF function.
1 |
SELECT *, IF( LENGTH(product_name) > 10, "LONG", "SHORT") AS result FROM Products; |
The query will return LONG if the product name length in the product_name column is greater than 10 characters, and SHORT if product_name column is smaller than 10 characters.
MySQL IF-ELSEIF-ELSE Statement
This allows using if, elseif and else statements to check the values in MySQL Stored Procedures.
MySQL If Usage;
1 2 3 |
IF Condition THEN -- Commands END IF; |
MySQL ElseIf Usage;
1 2 3 4 5 |
IF Condition THEN -- Commands ELSEIF Condition2 THEN -- Commands2 END IF; |
MySQL Else Usage;
1 2 3 4 5 |
IF Condition THEN -- Commands ELSE -- Commands2 END IF; |
1 2 3 4 5 6 7 8 |
IF Condition1 THEN -- Commands1 ELSEIF Condition2 THEN -- Commands2 ... ELSE -- Commands3 END IF; |
Below is an example of using if, elseif and else in stored procedures.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
DELIMITER // CREATE PROCEDURE NameSurname(IN mynumber INT, OUT status VARCHAR(50)) BEGIN IF mynumber = 1 THEN SET status = 'Yusuf'; ELSEIF mynumber = 2 THEN SET status = 'SEZER'; ELSEIF mynumber = 3 THEN SET status = 'Yusuf SEZER'; ELSE SET status = 'Yusuf Sefa SEZER'; END IF; END// DELIMITER ; |
In the example, the NameSurname stored procedure returns different status values according to the MyNumber parameter.
If the MyNumber parameter value is 1, the status parameter returns Yusuf, 2 if SEZER, 3 if Yusuf SEZER, if none, Yusuf Sefa SEZER.
Let’s run the stored procedure.
1 2 3 |
SET @result= 0; CALL NameSurname(99, @result); SELECT @result; |
When the stored procedure is executed, it will return “Yusuf Sefa SEZER”.