LESSON 62 / 62 · Operators IFOperators 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%';| id | name |
|---|---|
| 21 | Test Subject 1 |
| 22 | Test Subject 2 |
| 23 | Test 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.
Write a query and run it to see the results.
Write a query and run it to see the results.
Write a query and run it to see the results.