MySQL REPEAT Loop
The REPEAT loop in MySQL is a control flow structure that repeatedly executes a block of SQL statements until a specified condition evaluates to TRUE
. It is useful when you want to execute a loop at least once, regardless of the condition.
Syntax
label
(optional) → Used to reference the loop (helpful for nested loops).- Statements inside the loop execute at least once before checking the condition.
UNTIL condition
→ The loop runs until this condition evaluates toTRUE
.
Example: Using REPEAT to Print Numbers
Let's create a stored procedure that uses a REPEAT
loop to print numbers from 1 to 5.
Stored Procedure with REPEAT Loop
✅ Explanation:
- A variable
counter
is initialized to1
. - The loop executes once, then increments
counter
. - It stops executing when
counter
exceeds 5.
Calling the Procedure
📌 Output:
Use Case: Factorial Calculation
We can use a REPEAT
loop to calculate the factorial of a given number.
Calling the Procedure
✅ Output for 5!
(5 × 4 × 3 × 2 × 1 = 120)
Key Takeaways
✔ Ensures at least one execution (even if the condition is already met).
✔ Loops until a condition becomes TRUE
(opposite of WHILE
).
✔ Useful for simple iterations and incremental calculations.
✔ Must ensure termination to avoid infinite loops.
Would you like an example using nested REPEAT loops? 🚀