Introduction to MySQL WHILE LOOP
MySQL WHILE LOOP allows us with the benefit of executing one or multiple MySQL Statement queries repeatedly unless a condition is fulfilled to return the result value respectively. It is also known to be a pre-test conditional loop among the three-loop MySQL statements WHILE, LOOP, and REPEAT because here the search condition is tested initially before the code statement execution. WHILE loop when iteratively processed executes the SQL statements as result sets as long as the conditional expression is TRUE. Each statement in the WHILE loop terminates with the inclusion of a semicolon. The iteration of loop happens every time when the condition is examined and the result depends on the code flow. But if the MySQL WHILE loop condition is FLASE when the expression evaluates between while and end while statements then it exits the loop.
Syntax
The elementary syntax for WHILE loop is represented as follows:
[Label_to _begin:] WHILE SearchCondition DO
SQL statement(s)
END WHILE [Label_to_end]
Explanation to the above syntax terms:
- Using the label name, we can provide an optional label to the WHILE loop during the beginning or end of the MySQL execution of the query statement.
- A search condition is specified right after the WHILE keyword
- Then followed by iterations, the condition is checked at the very beginning.
- If it evaluates TRUE, then the WHILE loop moves forward to executes the other lists of statements until the result of the search condition generates to TRUE.
- Between the DO and END WHILE Loop keywords, one or multiple statements specified will be executed.
- If the WHILE evaluates FALSE then, the loop is terminated and ends.
- The loop works on stored programs and returns
Flowchart
We can better understand the MySQL WHILE loop process with the help of a flowchart. This diagrammatic illustration will make our concepts clear regarding the TRUE and FALSE evaluations in a WHILE loop and execution of SQL statements.
The flowchart specifies the essential arrangement of the WHILE loop iterative process in MySQL.
How does WHILE LOOP work in MySQL?
- From the above visual symbolic diagram, the WHILE loop algorithm in MySQL is represented in a simple design notion and meaning too.
- Firstly, the WHILE loop execution is started, for each loop iterations, the condition defined is evaluated, then based on the result of WHILE condition the SQL statement is determined. When the WHILE loop results in TRUE then, the code flow statements will be executed.
- Secondly, if the WHILE loop execution tends to produce any FALSE result according to the search condition then, the code flow will be withdrawaland the WHILE loop stops further processing. And suppose, if any SQL statement is available outside the WHILE loop then, it will be accomplished.
Example to Implement WHILE LOOP in MySQL
Let us discuss some of the examples of WHILE loop MySQL statements to execute the SQL query code as follows:
- For example, we are considering a table whose name is Calendar_Data to store the values of the WHILE loop and execute the statements accordingly. Let us now write the SQL query to create the MySQL table which will store the dates and other derived information such as year, month, day, and quarter. Here is the SQL CREATE Statement:
Code:
CREATE TABLE Calendar_Data (CID INT AUTO_INCREMENT, CDate DATE UNIQUE, CDay TINYINT NOT NULL, CMonth
TINYINT NOT NULL, CQuarter TINYINT NOT NULL, CYear INT
NOT NULL, PRIMARY KEY(CID));
- After this, we need to make a new stored procedure into the Calendar_Data table to enter a date value. The MySQL query for this is below:
Code:
DELIMITER $$
CREATE PROCEDURE EntryCalendar(cdt DATE)
BEGIN
INSERT INTO Calendar_Data(CDate, CDay, CMonth, CQuarter, CYear) VALUES(cdt, EXTRACT(DAY FROM cdt), EXTRACT(MONTH FROM cdt), EXTRACT(QUARTER FROM cdt),
EXTRACT(YEAR FROM cdt));
END$$
DELIMITER;
DELIMITER $$
- Now again, on the third step we will generate a new stored procedure again, i.e. LoadCalendar_Data() which is responsible to load a number of days into the Calendar_Data which is initialized by start date.
Code:
CREATE PROCEDURE LoadCalendar_Data(startDate DATE, day INT)
BEGIN
DECLARE counter INT DEFAULT 1;
DECLARE cdt DATE DEFAULT startDate;
WHILE counter <= day DO
CALL EntryCalendar(cdt);
SET counter = counter + 1;
SET cdt = DATE_ADD(cdt,INTERVAL 1 day);
END WHILE;
END$$
DELIMITER;
Here, the LoadCalendar_Data stored procedure comprises and accepts two parameters in the function:
- startData with DATE data type in MySQL denotes the start date to be inserted in the Calendar_Data table.
- day parameter in the procedure loads the number of days starting from the startDate into the table.
In this loading procedure:
- Before the WHILE loop begins, we firstly declare the variables counter and cdtto hold the immediate values. By default, the counter and cdt variables values are 1 and also startDatecorrespondingly.
- Now with the help of MySQL WHILE Loop, we will detect if the counter variable value is equal or less than day parameter value on execution.
If the result goes yes, then:
- The stored procedure is called i.e. EntryCalendar, to enter the row values in the Calendar_Datatable.
- Again, the loop iterates and counter is increased by one and the cdt is also increased by one day by the DATE_ADD() function in MySQL.
The WHILE loop repeats the counter condition unless the counter variable value is identical to the day parameter value and respectively inserts the date values into the columns in the Calendar_Datatable.
Example
Finally, we will use the following query statement to call the LoadCalendar_Data() stored procedure that holds 15 days row values records into the Calendar_Data table starting from 1st January 2020.
Code:
CALL LoadCalendar_Data('2020-01-01',10);
Using the SELECT keyword we can view the Calendar_Data records using WHILE loop and stored programs.
SELECT * FROM Calendar_Data;
Output:
Conclusion
A WHILE loop in MySQL works to execute a block of code statements while a search condition or say WHILE loop condition remains TRUE. When the part of code has a stated condition, the loop continues to execute the SQL part. Otherwise, the loop ends if no any WHILE condition occurs. WHILE loop is a MySQL stored program structure which implements to work fast.
Recommended Articles
This is a guide to MySQL WHILE LOOP. Here we discuss an introduction to MySQL WHILE LOOP with the working of loop and respective examples. You can also go through our other related articles to learn more –
12 Online Courses | 10 Hands-on Projects | 92+ Hours | Verifiable Certificate of Completion
4.5
View Course
Related Courses