Using FOR LOOP in Oracle

This Oracle tutorial explains how to use the FOR LOOP in Oracle with syntax and examples.

Description

In Oracle, the FOR LOOP approves you to execute code persistently for a fixed number of times.

Syntax

The syntax for the FOR Loop in Oracle/PLSQL is:

FOR loop_counter IN [REVERSE] lowest_number..highest_number
LOOP
   {...statements...}
END LOOP;

Parameters or Arguments

loop_counter The loop counter variable. REVERSE Optional. If specified, the loop counter will count number in reverse. lowest_number The starting cost for loop_counter. highest_number The ending cost for loop_counter. statements The statements of code to execute each skip via the loop.

Note

You would use a FOR LOOP when you desire to execute the loop physique a fixed number of times. If REVERSE is specified, then the highest_number will be the beginning value for loop_counter and lowest_number will be the ending price for loop_counter.

Example

Let’s seem at an instance of how to use a FOR LOOP in Oracle.

FOR Lcntr IN 1..20
LOOP
   LCalc := Lcntr * 31;
END LOOP;

This FOR LOOP example will loop 20 times. The counter known as Lcntr will begin at 1 and give up at 20.

You can use the REVERSE modifier to run the FOR LOOP in reverse order. For example:

FOR Lcntr IN REVERSE 1..15
LOOP
   LCalc := Lcntr * 31;
END LOOP;

This FOR LOOP instance will loop 15 times. However, due to the fact REVERSE is specified, the counter referred to as Lcntr will begin at 15 and give up at 1 (in essence, looping backwards).