MySQL WHILE Loop
The WHILE loop in MySQL repeatedly executes a block of SQL statements while a specified condition is TRUE
. If the condition is initially FALSE
, the loop will not execute at all.
Syntax
label
(optional) → A label for the loop, used in case of nested loops.condition
→ The condition that must beTRUE
for the loop to continue.DO
→ Specifies the block of statements to execute repeatedly.- The loop stops when the condition evaluates to
FALSE
.
Example: Using WHILE to Print Numbers
Let's create a stored procedure that uses a WHILE
loop to print numbers from 1 to 5.
Stored Procedure with WHILE Loop
✅ Explanation:
- The loop checks if
counter
is less than or equal to 5. - If the condition is
TRUE
, the loop printscounter
, then increments it by 1. - The loop stops when
counter
exceeds 5.
Calling the Procedure
📌 Output:
Use Case: Factorial Calculation Using WHILE
We can use the WHILE
loop to calculate the factorial of a number.
Calling the Procedure
✅ Output for 5!
(5 × 4 × 3 × 2 × 1 = 120):
Key Points
✔ Loop continues as long as the condition is TRUE
.
✔ No execution if the condition is initially FALSE
.
✔ Can be used for incremental tasks like calculations or iterative operations.
✔ Termination condition is critical to avoid infinite loops.
Would you like an example of a nested WHILE loop or infinite loop prevention? 🚀