Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
Loops in MySQL
Next article icon

MySQL WHILE Loop

Last Updated : 21 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this, we will cover the overview of MySQL WHILE Loop and then will cover the algorithm of each example and then will see the analysis of each example. Let's discuss it one by one.

Introduction :
MySQL WHILE loop statement is used to execute one or more statements again and again, as long as a condition is true. We can use the loop when we need to execute the task with repetition while condition is true.
Note - 
Use a WHILE LOOP statement in case you are unsure of what number of times you would like the loop body to execute. Since the WHILE condition is evaluated before entering the loop, it's possible that the loop body might not execute even once.

Syntax :

[label_name:] WHILE  condition DO    statements_list END WHILE [label_name]

Syntax label meaning -

  • Label_name - 
    label_name is optional, it's a name related to the WHILE loop.
  • Condition - 
    condition is tested each undergoes through the WHILE loop. If the condition results in TRUE, the statements_list is executed, or if the condition results in FALSE, the WHILE loop is terminated.
  • Statements_list - 
    Statements_list is that the list of statements to be executed withstand the WHILE loop.

Block diagram of While loop :

Block diagram of WHILE loop 

 

Examples of MySQL WHILE Loop :

Example-1 : 
Lets us create a function using a while loop.

DELIMITER $$ CREATE FUNCTION GeekInc ( value INT ) RETURNS INT BEGIN   DECLARE inc INT;   SET inc = 0;   label:  WHILE inc <= 30000 DO     SET inc = inc + value;   END  WHILE label;   RETURN inc; END; $$ DELIMITER ;

Analysis -

  • Value is the input for the GeekInc function.
  • inc is declared and set to 0.
  • While inc is less than and equal to 3000, it will set inc to inc + value.

To check output used the following command given below.

CALL GeekInc(10000);

Output -

0, 10000, 20000, 30000

Example-2 :
Let us create a procedure using a while loop.

DELIMITER $$ CREATE procedure while_ex() block: BEGIN  declare value VARCHAR(20) default ' ' ;  declare num INT default 0;  SET num = 1;  WHILE num <= 5 DO    SET value = CONCAT(value, num ,',' );    SET num = num + 1;  END  WHILE block;  select value ; END $$ DELIMITER ;

Analysis -

  • create procedure while_ex and declare value and num.
  • set num at 1, while num is equal to or less than 5 do
  • set value equal to concatenation of value and num.

To check output used the following command given below.

call while_ex();

Output -

value
1,2,3,4,5  

Example-3 : 
Let us create a table "Test_Cal" which has dates as follows.

CREATE TABLE Test_Cal(    t_in INT AUTO_INCREMENT,    fulldate DATE UNIQUE,    day TINYINT NOT NULL,    month TINYINT NOT NULL,    PRIMARY KEY(id) );

Now, create a stored procedure to insert data into the table as follows.

DELIMITER $$ CREATE PROCEDURE InsertCal(dt DATE) BEGIN    INSERT INTO Test_Cal(        fulldate,        day,        month )    VALUES(dt,          EXTRACT(DAY FROM dt),        EXTRACT(MONTH FROM dt)      ); END$$ DELIMITER ;

Now create stored procedure LoadCal() that updates the number of days starting from a start date into the table.

DELIMITER $$ CREATE PROCEDURE LoadCal(    startDate DATE,      day INT ) BEGIN       DECLARE counter INT DEFAULT 1;    DECLARE dt DATE DEFAULT startDate;    WHILE counter <= day DO        CALL InsertCal(dt);        SET counter = counter + 1;        SET dt = DATE_ADD(dt,INTERVAL 1 day);    END WHILE; END$$ DELIMITER ;

Analysis -

  • The stored procedure LoadCal() has two parameters: startDate and day.
  • First, declare a counter and dt variables for saving values.
  • Then, check if the counter is less than or equal day, if yes:
  • Run stored procedure Inertial() to insert a row into the Test_Cal table.
  • An increase in counter by 1 increases the dt by 1 day using the DATE_ADD().
  • The WHILE loop inserts date into the table till the counter is the same as the day.

To check output used the following command given below.

CALL LoadCal('2021-01-01',31); select * from Test_Cal where tid < 10 ;

Output -

t_idfulldatedaymonth
1 2021-01-0111
22021-01-0221
3 2021-01-0331
42021-01-0441
52021-01-0551
62021-01-0661
72021-01-0771
82021-01-0881
92021-01-0991

Next Article
Loops in MySQL

K

khushboogoyal499
Improve
Article Tags :
  • SQL
  • loop
  • DBMS-SQL
  • mysql

Similar Reads

  • Loops in MySQL
    In MySQL, loops are powerful constructs used to repeatedly execute a block of code or a set of statements until a specified condition is satisfied. MySQL supports various types of loop constructs, including the basic LOOP, WHILE and REPEAT loops along with flow control statements such as IF, CASE, I
    5 min read
  • SQL | WHERE Clause
    The SQL WHERE clause allows to filtering of records in queries. Whether you're retrieving data, updating records, or deleting entries from a database, the WHERE clause plays an important role in defining which rows will be affected by the query. Without it, SQL queries would return all rows in a tab
    4 min read
  • Floyd's triangle in PL/SQL
    Prerequisite - PL/SQL introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Floyd's triangle is a right-angled triangular array of
    2 min read
  • MySQL | Common MySQL Queries
    MySQL server is a open-source relational database management system which is a major support for web based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. Even all social networking websites mainly
    9 min read
  • PHP | MySQL Select Query
    The SQL SELECT statement is used to select the records from database tables. Syntax : The basic syntax of the select clause is - To select all columns from the table, the [Tex] * [/Tex] character is used. Implementation of the Select Query : Let us consider the following table ' Data ' with three co
    3 min read
  • PHP | MySQL LIMIT Clause
    In MySQL the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments which are offset and count.The value of both the parameters can be zero or positive integers. Offset:It is used to specify the offset of the fir
    3 min read
  • RIGHT() Function in MySQL
    RIGHT() function in MySQL is used to extract a specified number of characters from the right side of a given string. Second argument is used to decide, how many characters it should return. Syntax : RIGHT( str, len ) Parameter : This function accepts two parameter as mentioned above and described be
    3 min read
  • RLIKE operator in MySQL
    RLIKE : This operator in MySQL is used to performs a pattern match of a string expression against a pattern. Syntax : RLIKE pattern Parameters : This method accepts one parameter as mentioned in syntax. pattern -The pattern which we want to match against an expression. Various pattern and their usag
    2 min read
  • PHP | MySQL ORDER BY Clause
    The ORDER BY Clause can be used along with the SELECT statement to sort the data of specific fields in an ordered way. It is used to sort the result-set in ascending or descending order. Syntax : The basic syntax of the Order By clause is - Implementation of the Order By Clause : Let us consider the
    3 min read
  • MySQL | PARTITION BY Clause
    A PARTITION BY clause is used to partition rows of table into groups. It is useful when we have to perform a calculation on individual rows of a group using other rows of that group. It is always used inside OVER() clause. The partition formed by partition clause are also known as Window. This claus
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences