Skip to main content

PL/SQL Basic LOOP 🔄

Mentor's Note: A loop is like a Hamster Wheel. You keep running until you've reached your goal. The "Basic Loop" is the simplest type: it runs forever until you explicitly tell it to STOP. 💡


🌟 The Scenario: The Repetitive Task 🛠️

Imagine you are stamping 100 letters.

  • Action: Pick a letter -> Stamp it -> Check if you are done.
  • Loop: Keep repeating the action.
  • Exit: Stop once you have stamped the 100th letter. ✅

💻 1. The Basic Syntax

A basic loop starts with LOOP and ends with END LOOP;.

DECLARE
v_counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Iteration: ' || v_counter);

v_counter := v_counter + 1;

-- 🛑 The Exit Strategy (Mandatory to avoid infinite loop!)
IF v_counter > 5 THEN
EXIT;
END IF;
END LOOP;
END;

💻 2. The EXIT WHEN Clause (Shorthand)

A cleaner way to write the exit condition.

DECLARE
v_counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || v_counter);
v_counter := v_counter + 1;

EXIT WHEN v_counter > 5; -- ✅ Much more readable!
END LOOP;
END;

🏗️ Architect's Note: The Infinite Loop Danger 🛡️

If you forget to increment your counter or provide an EXIT condition, the loop will run until it crashes the session or uses up all the CPU.

  • Tip: Always double-check your exit condition. If your program seems to "hang" when you run it, you probably have an infinite loop!

🎨 Visual Logic: The Loop Cycle


📈 Learning Path

📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir