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:
Swift - While Loop
Next article icon

PL/SQL While Loop

Last Updated : 22 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Oracle PL/SQL provides various loop structures that help developers execute a block of code multiple times based on certain conditions. The main loop structures include LOOP ... END LOOP, WHILE ... END LOOP, and FOR ... END LOOP. In this article, we will explore the WHILE loop in detail, including its syntax, usage scenarios, and examples. We'll also discuss controlling the loop flow using statements like EXIT and EXIT WHEN.

What is a WHILE Loop in PL/SQL?

In PL/SQL, the WHILE loop statement is a control structure statement that repeatedly executes a code block that is inside the 'While Loop' as long as the specific condition set in the 'While Loop' is TRUE. The condition set in the 'WHILE' statement is a boolean expression that evaluates to TRUE, FALSE, or NULL. To terminate the loop prematurely or based on some specific scenario then the EXIT or EXIT WHEN statement is used.

The WHILE LOOP is used when you are not sure about the number of times the code block needs to execute. Only during the WHILE Loop execution, the specific condition set to end the execution is made TRUE and the control moves out of the WHILE Loop statement.

Syntax:

WHILE condition LOOP    -- Statements to be executed as long as the condition is true END LOOP;
  • condition: A Boolean expression that determines whether the loop will continue executing. If it evaluates to TRUE, the loop executes the block of code inside. If FALSE or NULL, the loop exits.
  • LOOP: Marks the beginning of the code block to be executed.
  • END LOOP: Marks the end of the loop block.

Examples of PL/SQL WHILE Loop

Let's look at some examples to better understand how to use the WHILE loop effectively in different scenarios.

Example 1: Using PL/SQL WHILE Loop for Iterative Execution

In this example, we look into the usage of the PL/SQL WHILE loop for iterative execution. The code demonstrates a basic scenario where a counter variable is initialized and incremented within the loop, with the loop executing until a specified condition is met.

DECLARE    counter NUMBER := 1;  -- Initialize a counter variable BEGIN    -- Start the WHILE loop    WHILE counter <= 5  -- Condition to check    LOOP       -- Statements to be executed as long as the condition is true       DBMS_OUTPUT.PUT_LINE('Counter value: ' || counter);              -- Increment the counter       counter := counter + 1;    END LOOP;  -- End of the loop END; / 

Explanation:

  • DECLARE: This section is used to declare variables. In this example, we declare a variable named counter and initialize it to 1.
  • BEGIN: Marks the beginning of the executable section.
  • WHILE Loop: The WHILE loop is used to repeatedly execute the block of statements as long as the specified condition (counter <= 5) is true.
  • LOOP: Marks the beginning of the loop block.
  • DBMS_OUTPUT.PUT_LINE: This statement is used to display output in the console. In this example, it prints the current value of the counter variable.
  • Increment Counter: The counter variable is incremented by 1 in each iteration.
  • END LOOP: Marks the end of the loop block.
  • END; Marks the end of the executable section.

In the above example, the WHILE loop will iterate as long as the counter is less than or equal to 5.

Output:

Statement processed. Counter value: 1 Counter value: 2 Counter value: 3 Counter value: 4 Counter value: 5

Example 2: Using EXIT WHEN for Loop Termination

This example illustrates the use of a PL/SQL WHILE loop with the EXIT WHEN statement, showcasing a scenario where the loop iterates until a certain condition is met. The code calculates the sum of numbers until the total sum reaches or exceeds 10.

DECLARE    total_sum NUMBER := 0;  -- Initialize a variable to store the sum    current_number NUMBER := 1;  -- Initialize a variable for the loop BEGIN    -- Start the WHILE loop with EXIT WHEN statement    WHILE total_sum < 10    LOOP       -- Add the current number to the total sum       total_sum := total_sum + current_number;        -- Display the current state       DBMS_OUTPUT.PUT_LINE('Current Number: ' || current_number);       DBMS_OUTPUT.PUT_LINE('Total Sum: ' || total_sum);              -- Increment the current number       current_number := current_number + 1;        -- Exit the loop when the total sum exceeds or equals 10       EXIT WHEN total_sum >= 10;    END LOOP;  -- End of the loop END; / 

Explanation:

  • The loop continues as long as total_sum is less than 10.
  • total_sum is updated by adding current_number in each iteration.
  • The EXIT WHEN statement exits the loop when total_sum reaches or exceeds 10.

Output:

Statement processed. Current Number: 1 Total Sum: 1 Current Number: 2 Total Sum: 3 Current Number: 3 Total Sum: 6 Current Number: 4 Total Sum: 10 

Important Points About PL/SQL While Loop

  • Unlike some programming languages, there is no built-in loop counter in a WHILE loop, so any counter must be manually incremented.
  • If the loop condition does not eventually evaluate to FALSE, the loop will continue indefinitely, potentially causing the program to hang.
  • When using nested WHILE loops, an EXIT statement only exits the current loop. To exit multiple nested loops, you would need to use multiple EXIT statements.
  • The EXIT or EXIT WHEN statements can be used to terminate the loop prematurely, providing more control over the loop execution.

Next Article
Swift - While Loop
author
julietmaria
Improve
Article Tags :
  • Geeks Premier League
  • Databases
  • PL/SQL
  • Geeks Premier League 2023

Similar Reads

  • PostgreSQL - While Loops
    When working with PostgreSQL, knowing how to efficiently use loops can be essential for running iterative operations. PostgreSQL’s WHILE loop allows developers to repeatedly execute a block of code as long as a specified condition remains true. PostgreSQL provides the loop statement which simply def
    4 min read
  • PL/SQL Loops
    PL/SQL stands for Procedural Language Extension to the Structured Query Language and it is designed specifically for Oracle databases it extends Structured Query Language (SQL) capabilities by allowing the creation of stored procedures, functions, and triggers. It is a block-structured language that
    5 min read
  • R - while loop
    While loop in R programming language is used when the exact number of iterations of a loop is not known beforehand. It executes the same code again and again until a stop condition is met. While loop checks for the condition to be true or false n+1 times rather than n times. This is because the whil
    5 min read
  • Rust - While Loop
    Loops in Rust come into use when we need to repeatedly execute a block of statements. Loops are also useful when we need to iterate over a collection of items. In Rust, we have various kinds of loops, including loops, while loops, and for loops. The while loop is the most common loop in Rust. The lo
    3 min read
  • Swift - While Loop
    Just like other programming languages, the working of the while loop in Swift is also the same. It is used to execute a target statement repeatedly as long as a given condition is true. And when the condition becomes false, the loop will immediately break and the line after the loop will execute. Wh
    2 min read
  • Solidity While Loop
    In Solidity, a while loop is a type of loop statement that allows you to execute a block of code repeatedly until a certain condition is met.  Syntax: while (condition) {    statement or block of code to be executed if the condition is True } The condition is an expression that is evaluated before e
    1 min read
  • While loop Syntax
    While loop is a fundamental control flow structure (or loop statement) in programming, enabling the execution of a block of code repeatedly as long as a specified condition remains true. Unlike the for loop, which is tailored for iterating a fixed number of times, the while loop excels in scenarios
    5 min read
  • Swift - Repeat While loop
    Sometimes there's a situation that comes when we have to execute a block of many numbers of times so to do this task we use the Repeat While loop. Or we can say that in Swift, we use the Repeat While loop to execute a block of code or a set of statements repeatedly. Repeat...while loop is almost sam
    3 min read
  • PL/SQL For Loop
    PL/SQL stands for Procedural Language/ Structured Query Language. It has block structure programming features. With PL/SQL, you can fetch data from the table, add data to the table, make decisions, perform repetitive tasks, and handle errors.PL/SQL supports SQL queries. To fetch records, process dat
    4 min read
  • SAP ABAP | While Loop
    A fundamental control structure in SAP ABAP is the while loop. The while loop in SAP ABAP can be used to iterate a part of code while the given condition remains true. This construct the while loop facilitates iterative running a block of code continues to execute until the specified condition withi
    3 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