PL/SQL For Loop

Sharing is Caring

PL/SQL For loop is used when we need to execute set of statements for the specific number of times and loop operates between the start and end counter values. The counter is always incremented by one and once the counter reaches to end integer value, the loop terminates

From Oracle Docs

FOR LOOP Statement
With each iteration of the FOR LOOP statement, its statements run, its index is either incremented or decremented, and control returns to the top of the loop. The FOR LOOP statement ends when its index reaches a specified value, or when a statement inside the loop transfers control outside the loop or raises an exception.

The syntax of PLSQL FOR Loop is like this

FOR counter_variable IN start value.. end value LOOP

statements to execute 

END LOOP;

Look at this example of PL/SQL FOR Loop

BEGIN
-- FOR Loop syntax and counter values
FOR i IN 1..9 LOOP
dbms_output.put_line('Value of- '||i);
END LOOP;
END;

and output is this, here you can see that loop starts from counter value 1 and ends at 9 as specified in the above block

REVERSE FOR Loop Example

We can reverse iteration of FOR loop using REVERSE keyword and as the word suggests this keyword executes the condition in reverse order. Here you can see a basic example of reverse For Loop.

BEGIN
-- FOR Loop syntax and counter values
FOR i IN REVERSE 1..9 LOOP
dbms_output.put_line('Value of- '||i);
END LOOP;
END;

and output is

PL/SQL For Loop

Cheers 🙂 Happy Learning

Related Posts

An Oracle ACE, Blogger, Reviewer, Technical Lead working on Oracle ADF

Leave a Reply

Your email address will not be published. Required fields are marked *