Sub topic 11
Counting with the Numeric FOR LOOP
This chapter assumes that you can declare variables, assign values, and run an anonymous PL/SQL block with DBMS_OUTPUT enabled. A numeric FOR loop repeats a statement block for each integer in a specified range.
The loop counter and range
A numeric FOR loop has this general form:
FOR counter IN lower_bound..upper_bound LOOP
statements;
END LOOP;PL/SQL creates the counter variable automatically. The counter is an integer, and its scope is the loop. You do not declare it separately or assign a value to it.
The loop includes both bounds. Therefore, 1..3 produces 1, 2, and 3.
BEGIN
FOR i IN 1..3 LOOP
DBMS_OUTPUT.PUT_LINE('i = ' || i);
END LOOP;
END;
/The output is:
i = 1
i = 2
i = 3The lower and upper bounds are evaluated when PL/SQL enters the loop. Changing another variable inside the loop does not change the range that the loop uses.
Counting backward with REVERSE
Add REVERSE to count from the upper bound down to the lower bound:
DECLARE
l_total PLS_INTEGER := 0;
BEGIN
FOR i IN REVERSE 1..4 LOOP
l_total := l_total + i;
DBMS_OUTPUT.PUT_LINE('Adding ' || i);
END LOOP;
DBMS_OUTPUT.PUT_LINE('Total: ' || l_total);
END;
/The counter values are 4, 3, 2, and 1. The output total is 10.
The range syntax remains lower_bound..upper_bound, even when using REVERSE. REVERSE 1..4 means “start at 4 and finish at 1.” It does not mean that you should write 4..1.
Empty ranges and common errors
Without REVERSE, a range whose lower bound is greater than its upper bound runs zero times. For example, 5..2 has no values.
With REVERSE, PL/SQL still uses the two bounds in their written order. REVERSE 5..2 also runs zero times because the resulting descending sequence would need to start at 2 and end at 5, which is not possible for that range.
The counter exists only inside the loop:
BEGIN
FOR day_number IN 1..3 LOOP
DBMS_OUTPUT.PUT_LINE(day_number);
END LOOP;
-- This would fail because day_number is out of scope here.
-- DBMS_OUTPUT.PUT_LINE(day_number);
END;
/Use a numeric FOR loop when the work is naturally based on a known sequence of integer values. If you need to stop based on a condition that changes during execution, consider a WHILE loop instead.
Exercise
What values does FOR i IN REVERSE 2..5 LOOP process, and how many iterations occur?
Show answer
It processes 5, 4, 3, and 2, for four iterations. Both bounds are included.