FOR (integer variant) v13

FOR <name> IN [REVERSE] <expression .. expression> LOOP
    <statements>
END LOOP;

This form of FOR creates a loop that iterates over a range of integer values. The variable name is automatically defined as type INTEGER and exists only inside the loop. The two expressions giving the loop range are evaluated once when entering the loop. The iteration step is +1 and name begins with the value of expression to the left of .. and terminates once name exceeds the value of expression to the right of ... Thus the two expressions take on the following roles: start-value.. end-value.

The optional REVERSE clause specifies that the loop should iterate in reverse order. The first time through the loop, name is set to the value of the right-most expression; the loop terminates when the name is less than the left-most expression.

The following example simplifies the WHILE loop example even further by using a FOR loop that iterates from 1 to 10.

BEGIN
    FOR i IN 1 .. 10 LOOP
        DBMS_OUTPUT.PUT_LINE('Iteration # ' || i);
    END LOOP;
END;

Here is the output using the FOR statement.

Iteration # 1
Iteration # 2
Iteration # 3
Iteration # 4
Iteration # 5
Iteration # 6
Iteration # 7
Iteration # 8
Iteration # 9
Iteration # 10

If the start value is greater than the end value the loop body is not executed at all. No error is raised as shown by the following example.

BEGIN
    FOR i IN 10 .. 1 LOOP
        DBMS_OUTPUT.PUT_LINE('Iteration # ' || i);
    END LOOP;
END;

There is no output from this example as the loop body is never executed.

Note

SPL also supports CURSOR FOR loops (see Cursor FOR Loop).