RienSQL
LESSON 62 / 62 · Operators IF

Operators IF, CASE, WHILE in stored procedures

Learn conditional statements and loops in SQL stored procedures and functions. Syntax and examples of IF, CASE, WHILE for MySQL and PostgreSQL.

IF, CASE, WHILE Operators in Stored Procedures

Stored procedures and functions are not just convenient containers for groups of queries. They allow you to implement quite complex logic using conditional operators and loops.

In this article, we'll explore the main flow control operators: conditional statements IF and CASE, as well as WHILE loops.

IF Conditional Statement

The IF operator allows you to execute code based on whether a condition is met.

IF Syntax

IF condition THEN
    statements
[ELSEIF condition THEN
    statements] ...
[ELSE
    statements]
END IF;
  • [ ]optional part
  • ...can be repeated

A logical expression, for example student_age < 18. The first branch whose condition is true runs, the rest are skipped.

One or more SQL statements, each ending with ;. They run if this branch is chosen.

Another branch with its own condition. It's checked only if all the conditions above are false. You can add several of these branches.

The branch that runs if none of the conditions turned out to be true.

ELSEIF
KeywordOptional
ELSE
KeywordOptional

IF Usage Example

Let's create a procedure that categorizes students by age:

CREATE PROCEDURE categorize_student_by_age(
    IN student_id INT,
    OUT category VARCHAR(20)
)
BEGIN
    DECLARE student_age INT;

    -- Get student age
    SELECT TIMESTAMPDIFF(YEAR, birthday, CURDATE())
    INTO student_age
    FROM Student
    WHERE id = student_id;

    -- Determine category by age
    IF student_age < 18 THEN
        SET category = 'Minor';
    ELSEIF student_age BETWEEN 18 AND 25 THEN
        SET category = 'Young';
    ELSE
        SET category = 'Adult';
    END IF;
END;

-- Use the procedure
CALL categorize_student_by_age(1, @category);
SELECT @category AS age_category;
age_category
Young

CASE Selection Statement

The CASE operator provides a more elegant way to handle multiple conditions.

CASE Syntax

CASE
    WHEN condition THEN result
    [WHEN ...]
    [ELSE default_result]
END
  • [ ]optional part
  • ...can be repeated

A logical expression checked in its own WHEN branch. There can be several branches: the first one whose condition is true wins.

The value returned when none of the conditions is met. Without ELSE, NULL is returned.

result
The value CASE takes if this branch's condition is true.
default_result
Optional

CASE Usage Example

Let's create the same student categorization procedure, but using the CASE operator:

CREATE PROCEDURE categorize_student_with_case(
    IN student_id INT,
    OUT category VARCHAR(20)
)
BEGIN
    DECLARE student_age INT;

    -- Get student age
    SELECT TIMESTAMPDIFF(YEAR, birthday, CURDATE())
    INTO student_age
    FROM Student
    WHERE id = student_id;

    -- Determine category using CASE
    SET category = CASE
        WHEN student_age < 18 THEN 'Minor'
        WHEN student_age BETWEEN 18 AND 25 THEN 'Young'
        ELSE 'Adult'
    END;
END;

-- Use the procedure
CALL categorize_student_with_case(1, @category);
SELECT @category AS age_category;
age_category
Young

WHILE Loop

The WHILE loop allows you to execute code repeatedly while a certain condition is met.

WHILE Syntax

WHILE condition DO
    statements
END WHILE;

A logical expression checked before each pass of the loop. The statements repeat while it's true.

The SQL statements in the loop body. One of them should eventually make the condition false, otherwise the loop never ends.

WHILE Usage Example

Let's look at an example of a stored procedure for creating several test subjects:

CREATE PROCEDURE create_test_subjects(IN count_subjects INT)
BEGIN
    DECLARE i INT DEFAULT 1;
    DECLARE subject_id INT DEFAULT 20;

    WHILE i <= count_subjects DO
        INSERT INTO Subject (id, name)
        VALUES
        (
            subject_id + i,
            CONCAT('Test Subject ', i)
        );

        SET i = i + 1;
    END WHILE;
END;

-- Create 3 test subjects
CALL create_test_subjects(3);

-- Check the result
SELECT * FROM Subject WHERE name LIKE 'Test Subject%';
idname
21Test Subject 1
22Test Subject 2
23Test Subject 3

Flow control operators make stored procedures and functions a powerful tool for implementing complex business logic directly in the database! 🚀

Practice

Solve it in the editor. The query runs against a sample database in your browser.

Task 1Function to determine user status
Create a stored function get_user_status that takes a parameter input_user_id of type INT and returns user status: "VIP" if they have more than 3 reservations, "Regular" if 1-3 reservations, "New" if no reservations. Use the IF operator.
SQL editor
SQLite
Ctrl / ⌘ + ↵
Result

Write a query and run it to see the results.

Task 2Price category
Create a stored function get_price_category that takes a price price of type INT and returns a category, a string of type VARCHAR(10): "budget" for a price below 100, "standard" for 100 to 199, "premium" from 200.
SQL editor
SQLite
Ctrl / ⌘ + ↵
Result

Write a query and run it to see the results.

Task 3Factorial
Create a stored function calc_factorial that takes a parameter n of type INT and returns its factorial of type BIGINT, the product of the numbers from 1 to n. For 0 the function returns 1.
SQL editor
SQLite
Ctrl / ⌘ + ↵
Result

Write a query and run it to see the results.