Oracle PL/SQL FOR LOOP with Example

What is For Loop?

"FOR LOOP" statement is best suitable when you want to execute a code for a known number of times rather than based on some other conditions.

In this loop, the lower limit and the higher limit will be specified and as long as the loop variable is in between this range, the loop will be executed.

The loop variable is self-incremental, so no explicit increment operation is needed in this loop. The loop variable need not to be declared, as it is declared implicitly.

FOR <loop_variable> in <lower_limit> .. <higher_limit> 
LOOP
<execution block starts>
.
.
.
<execution_block_ends>
 END LOOP;
Syntax Explanation:

Example 1: In this example, we are going to print number from 1 to 5 using FOR loop statement. For that, we will execute the following code.

Loops in PL/SQL

BEGIN
dbms Qutput.put linef.Prp.gram started.' );
FOR a IN 1 .. 5
LOOP
dbms_output.put_line(a);
END LOOP:
dbms_output.put_iine('Program completed.'); 
END;
/

Code Explanation:

Nested Loops

The loop statements can also be nested. The outer and inner loop can be of different types. In the nested loop, for every one iteration value of the outer loop, the inner loop will be executed fully.

Loops in PL/SQL

LOOP -outer
<execution block starts>
LOOP — inner
<execution_part> 
END LOOP; 
<execution_block_ends> 
END LOOP; 
Syntax Explanation:

Example 1: In this example, we are going to print number from 1 to 3 using FOR loop statement. Each number will be printed as many times as its value. For that, we will execute the following code.

Loops in PL/SQL

Loops in PL/SQL

DECLARE 
b NUMBER;
BEGIN
dbms output put line(‘Program started' );
FOR a IN 1..3 
LOOP
b:=1;
WHILE (a>=b)
LOOP
dbms output put line(a);
b:=b+1;
END LOOP;‭	
END LOOP;‭	‬
dbms_output.put_line('Program completed' );
END;
/

Code Explanation:

Summary

Loop FOR Loop
EXIT Criteria Exit when the counter reaches the limit
Usage Good to use when loop count to be executed is known.

 

YOU MIGHT LIKE: