Sub topic 11
Counting with the Numeric FOR LOOP
This chapter assumes you can write an anonymous PL/SQL block, declare scalar variables, and use EXIT WHEN in a basic LOOP. It covers the numeric FOR loop: its syntax, the rules for its counter and bounds, and the mistakes people make with it.
The shape of a numeric FOR loop
Use a numeric FOR loop when you know the number of iterations before the loop starts. The loop runs once for each integer from a lower bound to an upper bound.
BEGIN
FOR i IN 1..3 LOOP
DBMS_OUTPUT.PUT_LINE('i = ' || i);
END LOOP;
END;
/This prints i = 1, i = 2, and i = 3. The loop does the following for you:
- It declares the counter
i. You do not declare it in theDECLAREsection. - It starts the counter at the lower bound and adds 1 after each iteration.
- It stops when the counter would pass the upper bound.
- It removes the counter when the loop ends.
Compare this with a basic LOOP, where you declare the variable, initialize it, increment it, and write the exit test yourself. Each of those steps is a chance for an off-by-one error, and the FOR loop removes all of them.
Counting down with REVERSE
Add REVERSE to count from the upper bound down to the lower bound. The step is still 1, but it is subtracted.
BEGIN
FOR i IN REVERSE 1..3 LOOP
DBMS_OUTPUT.PUT_LINE('Countdown: ' || i);
END LOOP;
END;
/This prints 3, 2, 1. Always write the smaller number first, even with REVERSE. Writing REVERSE 3..1 is a common mistake. It does not count down. It produces an empty range, as the next section shows.
Rules for the bounds
The bounds follow a few rules that are easy to forget.
| Situation | Behavior |
|---|---|
| Lower bound greater than upper bound | The body never runs. No error is raised. |
| Lower bound equals upper bound | The body runs exactly once. |
| Bound is an expression or variable | It is evaluated once, before the first iteration. |
| Bound is not a whole number | PL/SQL rounds it to the nearest integer. |
| Bound is NULL | `VALUE_ERROR` (ORA-06502) is raised. |
Empty ranges
DECLARE
l_count PLS_INTEGER := 0;
BEGIN
FOR i IN 5..1 LOOP
l_count := l_count + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Iterations: ' || l_count);
END;
/This prints Iterations: 0. The empty range is useful. If you write FOR i IN 1..l_names.COUNT over a collection, an empty collection has a count of 0, so the loop is skipped without any special check.
Bounds are evaluated once
Changing a variable that supplied a bound does not change the loop that is already running.
DECLARE
l_high PLS_INTEGER := 3;
l_count PLS_INTEGER := 0;
BEGIN
FOR i IN 1..l_high LOOP
l_high := 10;
l_count := l_count + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Iterations: ' || l_count);
END;
/This prints Iterations: 3. If you want a bound that changes while the loop runs, use a WHILE loop or a basic LOOP instead.
NULL bounds
A NULL bound is not an empty range. It is an error. This matters when a bound comes from a column or a function that can return NULL.
DECLARE
l_limit PLS_INTEGER := NULL;
BEGIN
FOR i IN 1..l_limit LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('A NULL loop bound raises VALUE_ERROR');
END;
/Guard the value first, for example with NVL(l_limit, 0), if NULL is a realistic input.
Non-integer bounds
A bound such as 2.6 is rounded to 3, so FOR i IN 1..2.6 runs for 1, 2, and 3. Do not rely on this. It hides a calculation that probably should have used TRUNC or CEIL on purpose.
The counter is local and read-only
The counter exists only between LOOP and END LOOP. You can read it anywhere in the body, but you cannot assign to it. This code does not compile:
BEGIN
FOR i IN 1..3 LOOP
i := i + 1; -- PLS-00363: expression 'I' cannot be used as an assignment target
END LOOP;
END;
/You also cannot read the counter after the loop. If you need the last value, copy it into a variable you declared outside the loop.
DECLARE
l_last PLS_INTEGER;
BEGIN
FOR i IN 1..5 LOOP
l_last := i;
EXIT WHEN i * i > 10;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Last value reached: ' || l_last);
END;
/This prints Last value reached: 4. The loop stops when i is 4 because 16 is greater than 10. You can leave a FOR loop early with EXIT or EXIT WHEN, exactly as in a basic loop.
Shadowing an outer variable
If a variable outside the loop has the same name as the counter, the counter hides it inside the loop. It does not overwrite it. A block label lets you reach the outer one.
<<outer>>
DECLARE
i NUMBER := 100;
BEGIN
FOR i IN 1..2 LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || i || ', outer variable: ' || outer.i);
END LOOP;
DBMS_OUTPUT.PUT_LINE('After loop: ' || i);
END outer;
/The output is:
Counter: 1, outer variable: 100
Counter: 2, outer variable: 100
After loop: 100Avoid the situation entirely by giving counters distinct names such as i, j, or idx, and giving other variables prefixes such as l_.
Steps other than 1
Classic numeric FOR loops always move by 1. Newer database releases add a step option for the loop header. Check the documentation for your version before relying on it. These two techniques work in every version.
Skip unwanted values with CONTINUE WHEN:
BEGIN
FOR i IN 1..10 LOOP
CONTINUE WHEN MOD(i, 2) = 0;
DBMS_OUTPUT.PUT_LINE('Odd: ' || i);
END LOOP;
END;
/Or loop over a smaller range and compute the value you want. This one visits 1, 3, 5, 7, and 9 without wasting iterations:
BEGIN
FOR k IN 0..4 LOOP
DBMS_OUTPUT.PUT_LINE('Value: ' || (k * 2 + 1));
END LOOP;
END;
/The second form is the better choice when the range is large, because it runs half as many iterations.
A practical use: walking a date range
An integer counter combines well with date arithmetic. Adding a number to a DATE adds that many days.
DECLARE
l_start DATE := DATE '2026-11-23';
BEGIN
FOR d IN 0..6 LOOP
DBMS_OUTPUT.PUT_LINE(TO_CHAR(l_start + d, 'YYYY-MM-DD'));
END LOOP;
END;
/This prints seven consecutive dates, from 2026-11-23 to 2026-11-29.
Common errors
REVERSEwith swapped bounds.FOR i IN REVERSE 10..1runs zero times. WriteREVERSE 1..10.- Assigning to the counter. This is a compile-time error (PLS-00363). Use a separate variable or a different loop type.
- Expecting bounds to be re-read. They are evaluated once. A changed variable does not change the running loop.
- Using the counter after
END LOOP. It is out of scope. Copy it to an outer variable inside the loop. - NULL bounds. They raise
VALUE_ERRORrather than skipping the loop. - Sparse collections.
FOR i IN 1..t.COUNTassumes the indexes run 1 throughCOUNTwith no gaps. After deleting elements, uset.FIRST .. t.LASTand testt.EXISTS(i).
Exercise
What does this block print? Then change the loop header so it prints 4, 3, 2 using REVERSE. BEGIN FOR i IN 2..4 LOOP DBMSOUTPUT.PUTLINE(i); END LOOP; END;
Show answer
It prints 2, 3, and 4, one per line. To count down, write FOR i IN REVERSE 2..4 LOOP. The smaller bound still comes first, and the output is 4, 3, 2.
Exercise
A block declares ln PLSINTEGER := 3 and runs FOR i IN 1..ln LOOP, with the statement ln := l_n + 1 inside the body. How many times does the body run, and why?
Show answer
Three times. The bounds are evaluated once before the first iteration, so changing l_n inside the loop has no effect on the number of iterations.
Exercise
Why does FOR i IN 1..llimit raise an error when llimit is NULL, and how would you make the loop run zero times instead?
Show answer
A NULL loop bound raises VALUEERROR (ORA-06502) because PL/SQL cannot build a range from it. Replace the bound with NVL(llimit, 0). The range 1..0 is empty, so the body never runs.