MySQL IF-THEN-ELSE

In MySQL, the IF-THEN-ELSE statement is used to control the flow of a program or a query based on a specified condition. It is commonly employed within stored procedures, triggers, and functions to perform conditional logic.

Syntax

The basic syntax of the IF-THEN-ELSE statement in MySQL is as follows:

IF condition THEN
    -- statements to execute when the condition is true
ELSE
    -- statements to execute when the condition is false
END IF;

Here’s a breakdown of the components:

condition: This is the expression that evaluates to either true or false. If the condition is true, the statements inside the THEN block will be executed; otherwise, the statements inside the ELSE block (if present) will be executed.

THEN: This keyword is used to indicate the beginning of the block of statements to be executed if the condition is true.

ELSE: This keyword is optional and is followed by a block of statements. If the condition is false, the statements within the ELSE block will be executed.

END IF: This signifies the end of the entire IF-THEN-ELSE statement.

Example

Let’s look at a simple example to illustrate the usage:

DELIMITER //
CREATE PROCEDURE CheckAge(IN age INT)
BEGIN
    IF age >= 18 THEN
        SELECT 'You are an adult';
    ELSE
        SELECT 'You are a minor';
    END IF;
END //
DELIMITER ;

In this example, a stored procedure named CheckAge takes an integer parameter age. It uses the IF-THEN-ELSE statement to check whether the provided age is greater than or equal to 18. If the condition is true, it prints “You are an adult”; otherwise, it prints “You are a minor.”

You can call this stored procedure and pass an age as an argument to see the conditional logic in action:

CALL CheckAge(20);
-- Output: You are an adult

CALL CheckAge(15);
-- Output: You are a minor

This is a basic example, and you can use more complex conditions and statements within the IF-THEN-ELSE block based on your specific requirements.

The IF-THEN-ELSE statement in MySQL provides a powerful way to incorporate conditional logic into your SQL code, making it more versatile and adaptable to different scenarios.