EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MySQL Tutorial MySQL WHILE LOOP
Secondary Sidebar
MySQL Tutorial
  • Advanced
    • MySQL Formatter
    • MySQL TINYINT
    • MySQL Grant All Privileges
    • MySQL DROP TABLE
    • MySQL rename database
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL IF EXISTS
    • MySQL UUID
    • Views in MySQL
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL AES_Encrypt
    • MySQL Performance Tuning
    • MySQL Transaction
    • MySQL? sort_buffer_size
    • MySQL? Sync
    • MySQL? Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
    • MySQL Partitioning
    • MySQL InnoDB
    • MySQL Float vs Decimal
    • MySQL Union vs Union All
  • Basic
    • MySQL floor
    • MySQL DESCRIBE table
    • MySQL encryption
    • Introduction to MySQL
    • Is SQL Server a Database?
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • MySQL Community Server
    • How To Install MySQL
    • MySQL Versions
    • MySQL OpenSource
    • MySQL GUI Tools
    • MySQL Grant
    • MySQL Error 1064
    • MySQL Drop Database
    • MySQL not equal
    • MySQL SELECT INTO Variable
    • MySQL Commands
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • MYSQL COMMIT
    • MySQL FORMAT
    • Timestamp to Date in MySQL
    • MySQL DATEDIFF
    • MySQL?Incremental Backup
    • MySQL JSON Data Type
    • MySQL ENUM
    • MySQL Default Port
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL Cheat Sheet
    • MySQL ORDER BY Random
    • MySQL ORDER BY DESC
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
    • MySQL WHERE IN Array
    • MySQL Fetch Array
    • MySQL ISNULL
    • MySQL Index Types
    • Mysql? Export Schema
    • Amazon RDS for MySQL
    • MySQL greatest
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Functions
    • MySQL Function
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL IFNULL()
    • MySQL TIMESTAMPDIFF()
    • MySQL COALESCE()
    • MySQL count()
    • MIN() in MySQL
    • MySQL Numeric
    • MySQL field()
    • MySQL FIND_IN_SET()
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL Concat
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL Asynchronous
    • MySQL innodb_buffer_pool_size
    • MySQL key_buffer_size
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL Union
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • MySQL Clustered Index
    • MySQL? InnoDB Cluster
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • MySQL Optimize Table
    • TRUNCATE TABLE MySQL
    • MySQL Table Dump
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL LOWERCASE
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL AFTER UPDATE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL? INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL? Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MySQL DROP TRIGGER
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL?User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL?Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL Cluster
    • MySQL Partitioning
    • MySQL Full Text Search
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Interview Questions
    • MySQL Interview Questions

Related Courses

MS SQL Certification Courses

Oracle Certification Courses

PL/SQL Certification Courses

MySQL WHILE LOOP

By Aanchal SharmaAanchal Sharma

MySQL-WHILE-LOOP

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:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,171 ratings)
  • 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.

Flowchart

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:

MySQL WHILE LOOP - 2

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 –

  1. MySQL IN Operator
  2. Unique Key in MySQL
  3. MySQL Subquery
  4. ANY in MySQL
Popular Course in this category
MySQL Training Program (12 Courses, 10 Projects)
  12 Online Courses |  10 Hands-on Projects |  92+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

MS SQL Training (16 Courses, 11+ Projects)4.9
Oracle Training (14 Courses, 8+ Projects)4.8
PL SQL Training (4 Courses, 2+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more