EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

Loops in PL/SQL

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » Database Management Tutorial » Loops in PL/SQL

Loops-in-PL/SQL

Introduction to Loops in PL/SQL

Procedural Language/Structured Query Language or PL/SQL is Oracle Corporation’s procedural extension for the Oracle RDBMS. PL/SQL extended SQL by adding constructs used in procedural languages to enable more complex programming than SQL provides. Examples of these structures are IF…THEN…ELSE, basic loops, FOR loops, and WHILE loops.

Explain Different Types of Loops in PL/SQL

This article will explain you the iterative control structure means loops of PL/SQL; it will let you run the same code repeatedly. PL/SQL provides three different kinds of loop types:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

different types of loop in PL SQL

  • The simple or infinite loop
  • The FOR loop
  • The WHILE loop

Here, each loop is designed for a specific purpose, rules for use, and guidelines for high-quality creation.

Examples of Different Loops

Consider the following three procedures to understand different loops and their problem-solving ability in different ways.

1. The Simple Loop

This loop is as simple as its name. It starts with the LOOP keyword and ends with the end statement “END LOOP”.

Syntax 

LOOP
The sequence of statements;
END LOOP;

Here, as per the above syntax keyword, ‘LOOP’ marks the starting of the loop and ‘END LOOP’ stated the end of the loop. The sequence of statement part can contain any statement for execution.

Popular Course in this category
Sale
PL SQL Training (4 Courses, 2+ Projects)4 Online Courses | 2 Hands-on Projects | 17+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (8,890 ratings)
Course Price

View Course

Related Courses
SQL Training Program (7 Courses, 8+ Projects)Oracle Training (14 Courses, 8+ Projects)

Example of Simple loop

Let’s write a program to print the multiplication table of 18.

Loops in PL SQL

Here in the above loop, we do not have the “EXIT” statement; means the output execution will go on to infinite until we close this program manually.

Refer below program with Exit statement:

Loops in PL SQL 2

Explanation of the above program

In the declaration section, we have declared two variables; variable v_counter will serve as a counter and v_result will hold the result of the multiplication.

Down the execution section, we have our simple loop, here we have three statements.

  • The first statement will work as our update statement; this will update our counter and increment it by 1.
  • The second statement is an arithmetic expression, which will perform the multiplication of our table and will store the result in v_result variable.
  • The third statement is an output statement, which will print the result of the multiplication in a formatted manner.

Use of Exit Statement

As per exit statement if v_counter >=10 then loop with an exit which means the loop will execute 10 times.

Output:

Loops in PL_SQL 3

2. The FOR Loop

FOR loop allows you to execute the block of statements repeatedly for a fixed number of times.

Syntax

FOR loop_counter IN [REVERSE] lower_limit .. upper_limit LOOP
Statement1;
Statement2;
....Statement3;
END LOOP;

  • The first line of the syntax is the loop statement where keywords FOR marks the beginning of loop followed by loop counter which is an implicit index integer variable.
  • This means you do not need to define this variable in the declaration section, also it will increment itself by 1 implicitly on each iteration of your loop, unlike the other loops where we have to define loop counter.
  • Keyword IN is a must to be in the FOR Loop program.
  • Keyword REVERSE is not mandatory but always used in conjunction with Keyword IN.
  • If keyword REVERSE is used then the loop will iterate in the reverse order.
  • lower_limit and upper_limit are two integer numbers. These two variables define a number of iteration of the loop.
  • Two dots between these two variables serve as the range operator.
  • Then we have the body of the loop, which can be a statement or group of statements.
  • In the end, we have the phrase END LOOP that indicates the ending of the loop.

Example #1 

keywords FOR marks the beginning

Here as per the above program, we have our FOR loop which will print the value of the v_counter variable from 11 to 20.

Output:

keywords FOR marks the beginning output

Example #2: Now let’s print the same in reverse order using FOR loop.

reverse order using FOR loop

Just add keyword REVERSE after IN and before 11, this will execute the same o/p but in reverse order.

reverse order using FOR loop output

3. The WHILE Loop

While loop executes statements of program multiple times also this is best used for the program when no of iterations is unknown.

Syntax

WHILE condition LOOP
Statement 1;
Statement 2;
...
Statement N;
END LOOP;

  • Unlike another syntax WHILE loop, the syntax is very easy to understand. Here as per the above syntax, ‘WHILE’ marks beginning of the loop along with condition and ‘END LOOP’ stated the end of the loop.
  • The statements 1 through N are the executable statements, defined in the body of the loop. In addition, in the end, we have mentioned the END LOOP which indicates the end of the while loop.
  • In order to run statements inside the body of the While loop, the condition needs to be true.

Example: Print multiplication table of 17 using while loop.

Print multiplication table

  • In this example, we have the first variable “v_counter” that will serve as counter and the second variable is “v_result” this will hold the result of the multiplication.
  • Here the first statement is an arithmetic expression inside WHILE loop, which will be doing the task of table multiplication and result, will get stored in v_result.
  • The second statement is the print statement, which will print multiplication results. The third statement is update counter, which will update the counter with each iteration
  • This while loop will keep on working until we have counter value more than or equal to 10 and WHILE loop will get terminated post 10 counter value.

Output:

Print multiplication table output

Advantages of Loops in PL/SQL

  • Code Re-usability is the best advantage of loops, we do not need to write code repeatedly for each iteration, using loops we can re-use code in every iteration.
  • Loops also help us in reducing the code size or program size. All we have to do is just write one simple code and put that inside any loop to complete the work without coding for different outputs from the same program.
  • Complexity reduction has also added the advantage of loops.

Conclusion – Loops in PL/SQL

SQL is the only interface to a relational database, and PL/SQL is a procedural extension to SQL. It is important to understand how SQL works and to design databases and business logic correctly to get the right result set. PL/SQL can bSQe used inside the database, and it has many powerful features. There are many improvements to PL/SQL in Oracle Database 12.1. Use SQL whenever possible, but if your query gets too complicated or procedural features are needed, it is best to use PL/SQL instead.

Recommended Articles

This has been a guide to the Loops in PL/SQL. Here we also discuss advantages and different types of loops with examples. You may also have a look at the following articles to learn more–

  1. What is PL/SQL?
  2. MySQL Client
  3. MySQL REGEXP
  4. Loops in Shell Scripting

PL SQL Training (4 Courses, 2+ Projects)

4 Online Courses

2 Hands-on Projects

17+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Database Management Tutorial
  • PL/SQL
    • What is PL/SQL?
    • Careers in PL/SQL
    • PLSQL procedure
    • PL/SQL Exception
    • PL/SQL LIKE
    • PL/SQL Raise Exception
    • PLSQL rowtype
    • PLSQL? bind variables
    • PL/SQL Record
    • PL/SQL WITH
    • PL/SQL bulk collect
    • PL/SQL Block Structure
    • PL/SQL else if
    • PL/SQL nvl2
    • PL/SQL Package
    • PL/SQL exists
    • PL/SQL instr
    • PL/SQL listagg
    • PL/ SQL Formatter
    • PLSQLlength
    • PL/SQL Commands
    • PL/SQL Data Types
    • CASE statement in PL/SQL
    • PL/SQL IF Statement
    • Loops in PL/SQL
    • PL/SQL Add Column
    • For Loop in PLSQL
    • PL/SQL Cursor Loop
    • PLSQL Array
    • Cursors in PL/SQL
    • PL/SQL FOR Loop Cursor
    • PL/SQL Queries
    • PL/SQL SELECT INTO
    • PL/SQL TO_CHAR
    • PL/SQL UNION
    • PL/SQL NOT EQUAL
    • PL/SQL varray
    • PL/SQL Concatenate
    • PL/SQL UPDATE
    • PL/SQL TRIM
    • PL/SQL GROUP BY
    • PL/SQL GOTO
    • PL/SQL Date Functions
    • PL/ SQL having
    • PL/SQL to_DATE
    • PL/SQL NVL
    • PLSQL format date
    • PLSQL mod
    • PLSQL round
    • PL/SQL Boolean
    • PL/SQL exit
    • PL/SQL DECODE
    • PL/SQL ROWNUM
    • PLSQL?pivot
    • PLSQL string functions
    • PL/SQL Block
    • PL/SQL Function
    • PL/SQL Unwrapper
    • PL/SQL Table
    • PL/SQL ALTER TABLE
    • PLSQL execute immediate
    • Triggers in PL/SQL
    • PL/SQL Collections
    • PL/SQL stored procedure
    • PL/SQL Anonymous Block
    • PLSQL Interview Questions
  • DataBase Management
    • Text Data Mining
    • Roles of Database Management System in Industry
    • SQL Server Database Management Tools
    • Database administrator skills
    • Database Management Systems Advantages
    • Database Testing Interview Questions
    • Data Administrator
    • Database Administrator
    • Database Management Software
    • DataStage
    • Types of Database Models
    • Types of Database
    • Hierarchical Database Model
    • Relational Database
    • Relational Database Advantages
    • Operational Database
    • What is RDBMS?
    • What is DB2?
    • Data Masking Tools
    • Database Security
    • Data Replication
    • Bitmap Indexing
    • Second Normal Form
    • Third Normal Form
    • Fourth Normal Form
    • Data Definition Language
    • Data Manipulation Language
    • Data Control Language
    • Transaction Control Language
    • Conceptual Data Model
    • Entity-Relationship Model
    • Relational Database Model
    • Sequential File Organization
    • Checkpoint in DBMS
    • Teradata Create Table
    • Centralized Database
    • Data Storage in Database
    • Thomas write Rule
    • DBA Interview Questions
    • What is JDBC?
    • jdbc hive
    • Apriori Algorithm
    • JDBC Architecture
    • JDBC Interview Questions
    • Wildcard Characters
    • Distributed Database System
    • Multidimensional Database
  • TSQL Basic
    • TSQL
    • What is T-SQL
    • T-SQL Commands
    • T-SQL String Functions
    • TSQL Interview Questions
  • MariaDB
    • MariaDB Versions
    • MariaDB?list users
    • MariaDB Commands
    • MariaDB odbc
    • MariaDB Workbench
    • MariaDB for windows
    • MariaDB Server
    • MariaDB? Data Types
    • MariaDB?boolean
    • MariaDB phpMyAdmin
    • MariaDB Mysqldump
    • MariaDB Java Connector
    • MariaDB insert
    • MariaDB UPDATE
    • MariaDB? rename column
    • MariaDB AUTO_INCREMENT
    • MariaDB Timezone
    • MariaDB GROUP_CONCAT
    • MariaDB wait_timeout
    • MariaDB MaxScale
    • MariaDB? with
    • MariaDB? create?table
    • MariaDB? SHOW TABLES
    • MariaDB alter table
    • MariaDB List Tables
    • MariaDB JSON Functions
    • MariaDB Foreign Key
    • MariaDB? trigger
    • MariaDB Grant All Privileges
    • MariaDB Select Database
    • MariaDB? create database
    • MariaDB Delete Database
    • MariaDB List Databases
    • MariaDB Functions
    • MariaDB? TIMESTAMP
    • MariaDB create user
    • MariaDB add user
    • MariaDB show users
    • MariaDB Delete User
    • MariaDB? change user password
    • MariaDB? change root password
    • MariaDB reset root password
    • MariaDB IF
    • MariaDB bind-address
    • MariaDB Transaction
    • MariaDB Cluster
    • MariaDB Logs
    • MariaDB Encryption
    • MariaDB? backup
    • MariaDB Replication
    • MariaDB max_allowed_packet
    • MariaDB? performance tuning
    • MariaDB export database
    • MariaDB? import SQL
  • SQLite
    • What is SQLite
    • SQLite Commands
    • SQLite Data Types
    • SQLite COUNT
    • SQLite Boolean
    • SQLite autoincrement
    • SQLite select
    • SQLite? Bulk Insert
    • SQLite? add column
    • SQLite? concat
    • SQLite BETWEEN
    • SQLite group by
    • SQLite CASE
    • SQLite group_concat
    • SQLite array
    • SQLite? enum
    • SQLite sum
    • SQLite create table
    • SQLite Alter Table
    • SQLite Create Database
    • SQLite Delete
    • SQLite connection string
    • SQLite Database
    • SQLite Describe Table
    • SQLite Show Tables
    • SQLite exit
    • SQLite create index
    • SQLite foreign key
    • SQLite Stored Procedures
    • SQLite Extension
  • DB2
    • DB2? current date
    • DB2 purescale
    • DB2 backup
    • DB2 restore
    • DB2 C Express
    • DB2 Version
    • DB2? Architecture
    • DB2? Data Types
    • DB2? load
    • DB2? order by
    • DB2 date
    • DB2 NVL
    • DB2? update
    • DB2 warehouse
    • DB2 grant
    • DB2 database
    • DB2 VARCHAR
    • DB2? INSERT
    • DB2 LISTAGG
    • DB2 LIKE
    • DB2 TRUNCATE TABLE
    • DB2 LIST TABLES
    • DB2 between
    • DB2? current timestamp
    • DB2? length
    • DB2? bind
    • DB2 limit rows
    • DB2? export
    • DB2 with
    • DB2 Create Table
    • DB2 case statement
    • DB2 CAST
    • DB2 Functions
    • DB2 Date Functions
    • DB2? row_number
    • DB2 trim
    • DB2? Translate
    • DB2 UNION
    • DB2 timestamp
    • DB2? TIMESTAMPDIFF
    • DB2? replace
    • DB2 merge
    • DB2 COALESCE
    • DB2 ISNULL
    • DB2? explain
    • DB2 Join
    • DB2 alter column
    • DB2 rename column
    • DB2? Describe Table
    • DB2? rename table
    • DB2 List Databases
    • DB2 LUW
    • DB2 Query
    • DB2 GROUP BY
    • DB2 TO_DATE
    • View Serializability in DBMS
    • MariaDB Join
    • MariaDB JSON
    • MariaDB? show databases
    • Dataset Normalization
    • MariaDB Max Connections
    • jdbc connection
    • MariaDB GUI
  • DBMS
    • Introduction To DBMS
    • DBMS ER Diagram
    • What is DBMS?
    • DBMS join
    • DBMS Functions
    • Data Administrator in DBMS
    • DBMS Canonical Cover
    • DBMS Log-Based Recovery
    • DBMS Multivalued Dependency
    • Netezza Database
    • DBMS Concepts
    • DBMS Constraints
    • DBMS_Scheduler
    • B+ Tree in DBMS
    • DBMS_LOB
    • dbms entity
    • DBMS Foreign Key
    • DBMS Users
    • DBMS_Metadata.get_ddl
    • Relational Algebra in DBMS
    • DBMS Components
    • DBMS Features
    • DBMS Models
    • DBMS Relational Model
    • Hashing in DBMS
    • DBMS network model
    • Relationship in DBMS
    • ER Model in DBMS
    • Data Models in DBMS
    • Static Hashing in DBMS
    • Advantages of DBMS
    • dbms_output.put_line
    • DBMS Data Dictionary
    • dbms_xplan.display_cursor
    • Normal Forms in DBMS
    • DBMS helps achieve
    • DBMS 3 tier Architecture
    • Relational Calculus in DBMS
    • Serializability in DBMS
    • File Organization in DBMS
    • DBMS Transaction Processing
    • States of Transaction in DBMS
    • Functional Dependency in DBMS
    • Generalization in DBMS
    • Data Independence in DBMS
    • Lock Based Protocols in DBMS
    • Deadlock in DBMS
    • Integrity Constraints in DBMS
    • Concurrency Control in DBMS
    • Validation Based Protocol in DBMS
    • DBMS Locks
    • Normalization in DBMS
    • Transaction Property in DBMS
    • Specialization in DBMS
    • Aggregation in DBMS
    • Types of DBMS

Related Courses

SQL Certification Course

PL/SQL Certification Course

Oracle Certification Course

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

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

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
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.

Let’s Get Started

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

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

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

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.

Special Offer - PL SQL Training (4 Courses, 2+ Projects) Learn More