Oracle PL/SQL - FOR LOOP Statement

Introduction

The FOR LOOP statement runs one or more statements while the loop index is in a specified range.

The statement has this structure:

[ label ] FOR index IN [ REVERSE ] lower_bound..upper_bound LOOP 
  statements 
END LOOP [ label ]; 

Without REVERSE, the value of index starts at lower_bound and increases by one with each iteration of the loop until it reaches upper_bound.

If lower_bound is greater than upper_bound, then the statements never run.

With REVERSE, the value of index starts at upper_bound and decreases by one with each iteration of the loop until it reaches lower_bound.

If upper_bound is less than lower_bound, then the statements never run.

An EXIT, EXIT WHEN, CONTINUE, or CONTINUE WHEN in the statements can cause the loop or the current iteration of the loop to end early.

In the following code, index is i, lower_bound is 1, and upper_bound is 3. The loop prints the numbers from 1 to 3.

Demo

SQL>
SQL> BEGIN-- ww w.j a  v a  2 s . c  om
  2    DBMS_OUTPUT.PUT_LINE ('lower_bound < upper_bound');
  3
  4    FOR i IN 1..3 LOOP
  5      DBMS_OUTPUT.PUT_LINE (i);
  6    END LOOP;
  7
  8    DBMS_OUTPUT.PUT_LINE ('lower_bound = upper_bound');
  9
 10    FOR i IN 2..2 LOOP
 11      DBMS_OUTPUT.PUT_LINE (i);
 12    END LOOP;
 13
 14    DBMS_OUTPUT.PUT_LINE ('lower_bound > upper_bound');
 15
 16    FOR i IN 3..1 LOOP
 17      DBMS_OUTPUT.PUT_LINE (i);
 18    END LOOP;
 19  END;
 20  /
lower_bound < upper_bound
1
2
3
lower_bound = upper_bound
2
lower_bound > upper_bound

PL/SQL procedure successfully completed.

SQL>

Related Topics

Quiz