Loops in MySQL
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
In MySQL, loops let you repeat a sequence of statements until a certain condition is met. You can use them to repeat execution of code blocks in stored procedures, functions and triggers.
MySQL supports three main types of loops: LOOP, REPEAT, and WHILE. Each serves a different purpose and is used based on the logic requirements.
The LOOP statement is the simplest form of loop in MySQL. It runs indefinitely until it encounters a LEAVE statement.
LOOP_NAME: LOOP
-- Statements to be executed
IF condition THEN
LEAVE LOOP_NAME;
END IF;
END LOOP LOOP_NAME;
The REPEAT loop executes until a specified condition is true. It checks the condition after executing the loop’s statements.
REPEAT
-- Statements to be executed
UNTIL condition
END REPEAT;
The WHILE loop executes as long as a specified condition is true, checking the condition before each iteration.
WHILE condition DO
-- Statements to be executed
END WHILE;
Loops are commonly used in stored procedures. Here’s an example of using a WHILE loop within a stored procedure:
DELIMITER //
CREATE PROCEDURE LoopDemo()
BEGIN
DECLARE v1 INT DEFAULT 5;
WHILE v1 > 0 DO
-- Perform actions
SET v1 = v1 - 1;
END WHILE;
END //
DELIMITER ;
Control statements like LEAVE and ITERATE are used to control the flow of loops.
LEAVE exits the loop when a certain condition is met. It is useful in LOOP and WHILE loops.
WHILE condition DO
IF exit_condition THEN
LEAVE loop_name;
END IF;
-- Loop statements
END WHILE loop_name;
ITERATE skips the current loop iteration and starts the next one. It is particularly useful in LOOP and WHILE loops.
WHILE condition DO
IF skip_condition THEN
ITERATE loop_name;
END IF;
-- Loop statements
END WHILE loop_name;
Nested loops, where one loop is placed inside another, are particularly useful for processing multi-dimensional data. Here’s an example:
DECLARE outer_counter INT DEFAULT 1;
DECLARE inner_counter INT DEFAULT 1;
WHILE outer_counter <= 5 DO
WHILE inner_counter <= 3 DO
-- Inner loop actions
SET inner_counter = inner_counter + 1;
END WHILE;
SET inner_counter = 1;
-- Outer loop actions
SET outer_counter = outer_counter + 1;
END WHILE;
Basedash is built as an AI-native BI platform, so teams can go from ad hoc SQL to trusted answers and dashboards quickly, without the overhead of traditional BI setup.
Written by
Senior Engineer at Basedash
Robert Cooper is a senior engineer at Basedash who builds full-stack product systems across SQL data infrastructure, APIs, and frontend architecture. His work focuses on application performance, developer velocity, and reliable self-hosted workflows that make data operations easier for teams at scale.
Basedash lets you build charts, dashboards, and reports in seconds using all your data.