PL/SQL Numeric FOR LOOP π’¶
Mentor's Note: The
FORloop is the most predictable loop. It's like a train track with a fixed start and end station. You tell it "Go from 1 to 10," and it does exactly thatβno more, no less. π‘
π The Scenario: The School Assembly π¶
Imagine a teacher counting students. - Task: Count from student 1 to student 50. - Rule: You don't stop until you reach 50. - The Loop: It handles the counting for you automatically.
π» 1. The Basic Syntax¶
The counter variable (index) is automatically declared by the loop. You don't need to add it to your DECLARE section!
BEGIN
-- π Logic: Start at 1, End at 5
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Student number: ' || i);
END LOOP;
END;
π» 2. The REVERSE Keyword π¶
If you want to count backwards, use REVERSE. Note: The range must still be written Small..Large.
BEGIN
-- π Logic: Count 5, 4, 3, 2, 1
FOR i IN REVERSE 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Countdown: ' || i);
END LOOP;
END;
ποΈ Architect's Note: Loop Scope π‘οΈ¶
- Automatic Counter: The index variable
ionly exists inside the loop. You cannot use it afterEND LOOP;. - Read-Only: You cannot change the value of
imanually (e.g.,i := i + 5is not allowed!). Oracle manages it. - Upper Bound: If the starting number is larger than the ending number (e.g.,
10..1), the loop will not run at all (unless you useREVERSE).
π¨ Visual Logic: The Fixed Track¶
graph LR
A[Start: 1] --> B[2]
B --> C[3]
C --> D[4]
D --> E[End: 5]