MySQL – How to Write Loop in MySQL

Posted by Pinal Dave on SQL Authority See other posts from SQL Authority or by Pinal Dave
Published on Tue, 12 Nov 2013 01:30:40 +0000 Indexed on 2013/11/12 4:01 UTC
Read the original article Hit count: 276

Since, I have written courses on MySQL, I quite often get emails about MySQL courses. Here is the question, which I have received quite often.

“How do I loop queries in MySQL?”

Well, currently MySQL does not allow to write loops with the help of ad-hoc SQL. You have to write stored procedure (routine) for the same.

Here is the example, how we can create a procedure in MySQL which will look over the code. In this example I have used SELECT 1 statement and looped over it. In reality you can put there any code and loop over it. This procedure accepts one parameter which is the number of the count the loop will iterate itself.

delimiter //
label1: LOOP
SET p1 = p1 - 1;
IF p1 > 0 THEN
ITERATE label1;
LEAVE label1;
END LOOP label1;
delimiter ;
CALL doiterate(100);

You can also use WHILE to loop as well, we will see that in future blog posts.

Reference: Pinal Dave (

Filed under: MySQL, PostADay, SQL, SQL Authority, SQL Query, SQL Tips and Tricks, T SQL

© SQL Authority or respective owner

Related posts about mysql

Related posts about PostADay