Skip to content

PL/SQL Numeric FOR LOOP πŸ”’

Mentor's Note: The FOR loop 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 πŸ›‘οΈ

  1. Automatic Counter: The index variable i only exists inside the loop. You cannot use it after END LOOP;.
  2. Read-Only: You cannot change the value of i manually (e.g., i := i + 5 is not allowed!). Oracle manages it.
  3. 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 use REVERSE).

🎨 Visual Logic: The Fixed Track

graph LR
    A[Start: 1] --> B[2]
    B --> C[3]
    C --> D[4]
    D --> E[End: 5]

πŸ“ˆ Learning Path