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:
Solidity For Loop
Next article icon

PL/SQL For Loop

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

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 data, or execute complex calculations, the FOR loop helps to efficiently iterate over a range of values or collections

Here, we look into the versatility of the PL/SQL FOR loop, a key construct for procedural programming in Oracle databases, explore its syntax, provide examples of its application, demonstrate the use of the REVERSE keyword for reverse iteration, and discuss the effectiveness of nested FOR loops.

FOR LOOP in PL/SQL

Along with SQL queries PL/SQL supports looping. FOR loop is a type of control statement. It is used to perform repetitive tasks. It is used to execute the set of statements for a specific number of times. To execute for loop, start and end values are provided. During each iteration counter is incremented by 1.

Syntax

DECLARE         --declare loop variable and provide its datatype loop_varaible datatype; BEGIN         --for loop with start and end value FOR loop_variable in start_value .. end_value LOOP set of statements  END LOOP; END; /

The loop_variable automatically increments by 1 in each iteration, and the loop continues until it reaches the end_value. There's no need to declare the loop variable separately unless needed elsewhere in the program

Example: Print Number From 1 to 5 Using FOR Loop in PL/SQL

Here’s a simple example to demonstrate the PL/SQL FOR loop:

Query:

SET SERVEROUTPUT ON; DECLARE counter NUMBER; BEGIN DBMS_OUTPUT.PUT_LINE('PL/SQL FOR LOOP EXECUTION'); FOR counter IN 1..5 LOOP     DBMS_OUTPUT.PUT_LINE('COUNTER VALUE: '|| counter); END LOOP; END; / 

Output:

PLSQL-FOR-LOOP
PL/SQL FOR LOOP

Explanation:

  • SET SERVEROUTPUT ON is used to enable output in Oracle SQL*Plus or other tools.
  • The loop variable counter is automatically initialized and used within the loop to print numbers from 1 to 5.
  • The FOR loop iterates over the range from 1 to 5 and displays the output using DBMS_OUTPUT.PUT_LINE.

PL/SQL NESTED FOR LOOP

PL/SQL supports nested for loop. The nested for loop contains an outer loop and one or more inner loop. For each increment of the loop variable , of the outer loop, the inner loops executes the set of statements within it for a specific number of times.This process repeats until loop variable of outer loop reaches its end value.Nested for loops are used for executing complex operations, designing patterns, and many more operations.

Syntax

BEGIN           --outer loop  FOR loop_variable1 IN start_value1 ..end_value1 LOOP           --inner loop FOR  loop_variable2 IN start_value2 ..end_value2 LOOP           --set of statements  END LOOP;           --inner loop end END LOOP;           --outer loop end END; /

Example: Using Nested FOR Loops to Print a Pattern

In this example, we will print the numbers 1, 2, and 3 in a pattern using nested loops.

Query:

SET SERVEROUTPUT ON; BEGIN     DBMS_OUTPUT.PUT_LINE('PL/SQL NESTED FOR LOOP EXECUTION');     FOR counter IN 1..3 LOOP         FOR counter1 IN 1..3 LOOP             DBMS_OUTPUT.PUT( counter1);         END LOOP;         DBMS_OUTPUT.NEW_LINE;     END LOOP; END; / 

Output:

PLSQL-NESTED-FOR-LOOP
PLSQL NESTED FOR LOOP

Explanation:

  • The outer loop runs three times, and for each iteration of the outer loop, the inner loop runs three times, printing the values from 1 to 3.
  • DBMS_OUTPUT.NEW_LINE is used to move to a new line after the inner loop finishes.

Using the REVERSE Keyword in a PL/SQL FOR Loop

Reverse keyword is used in FOR loop to iterate from end value to start value.REVERSE keyword is mentioned before the start value.

Syntax

BEGIN
FOR loop_variable IN REVERSE start_value .. end_value LOOP
set_of_statements
END LOOP;
END;
/

Example: Print Number From 5 to 1 Using the REVERSE Keyword

Here’s how you can print numbers in reverse order using a FOR loop:

Query:

SET SERVEROUTPUT ON; DECLARE counter NUMBER; BEGIN DBMS_OUTPUT.PUT_LINE('FOR LOOP WITH REVERSE KEYWORD'); FOR counter IN REVERSE 1..5 LOOP     DBMS_OUTPUT.PUT_LINE('REVERSE VALUE: '|| counter); END LOOP; END; / 

Output:

FOR-LOOP-WITH-REVERSE-KEYWORD
FOR LOOP WITH REVERSE KEYWORD

Explanation:

  • The REVERSE keyword is used to reverse the iteration, starting from 5 and decrementing to 1.
  • The loop prints the numbers in descending order.

Important Points About PL/SQL For Loop

  • The loop variable is automatically declared and incremented within the FOR loop, so there's no need for explicit initialization or incrementation.
  • The loop iterates from a specified start_value to end_value. The loop variable increases by 1 after each iteration.
  • The loop variable is scoped to the loop itself. It cannot be accessed outside the loop unless explicitly declared in the declaration section.
  • The REVERSE keyword can be used to iterate in reverse order, starting from the higher value and decrementing to the lower value.



Next Article
Solidity For Loop

P

pritamvinodfulari
Improve
Article Tags :
  • Geeks Premier League
  • Databases
  • PL/SQL
  • Geeks Premier League 2023

Similar Reads

  • 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
  • PL/SQL Cursor FOR LOOP
    Oracle PL/SQL is a powerful extension of SQL, specifically designed to provide procedural capabilities for Oracle databases. It allows developers to write complex programs that combine SQL queries with procedural constructs like loops, conditionals, and exception handling. Among these features, PL/S
    4 min read
  • PostgreSQL - For Loops
    In PostgreSQL, PL/pgSQL (Procedural Language/PostgreSQL) introduces control structures like FOR loops to simple complex data processing. The FOR loop allows developers to iterate over a specified range of integers or the results of a query and making repetitive tasks more manageable. This feature is
    6 min read
  • PL/SQL While Loop
    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 i
    5 min read
  • Solidity For Loop
    This is the most compact way of looping. It takes three arguments separated by a semi-colon to run. The for loop includes three most important parts: Loop Initialization: The first one is 'loop initialization' where the iterator is initialized with starting value, this statement is executed before t
    2 min read
  • For loop Syntax
    For loop is a control flow statement in programming that allows you to execute a block of code repeatedly based on a specified condition. It is commonly used when you know how many times you want to execute a block of code. Table of Content For loop Syntax in C/C++For loop Syntax in JavaFor loop Syn
    5 min read
  • PL/SQL Left Join
    In the world of database management, efficiently retrieving and combining data from multiple tables is crucial. Among these the LEFT JOIN is particularly important because it includes all records from one table even when there are no corresponding records in another table. In this article, we will P
    6 min read
  • PL/SQL NOT Operator
    PL/SQL, an extension of SQL in Oracle, offers various operators that allow us to perform logical operations on data. One such operator is the NOT operator, which is used to negate a condition, meaning it will return true if the condition is false and vice versa. The NOT operator is commonly used in
    6 min read
  • PL/SQL Full Join
    A FULL JOIN, also called a FULL OUTER JOIN, is a type of join in PL/SQL that returns all rows from both tables, even if there is no matching data in the other table. If a row from one table doesn’t have a match in the other, it will still be included in the result, with NULL values filling in the mi
    6 min read
  • For loop in R
    For loop in R Programming Language is useful to iterate over the elements of a list, data frame, vector, matrix, or any other object. It means the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the object. It is an entry-controlled loop, in
    5 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