Skip to content

PL/SQL WHILE Loop 🔄❓

Mentor's Note: The WHILE loop is a "Look before you leap" loop. It checks the condition before doing any work. If the condition is false at the start, the loop doesn't run even once! 💡


🌟 The Scenario: The Coffee Shop ☕

Imagine you are a waiter serving coffee. - Condition: Is there a customer in the queue? - Action: Serve coffee. - The Loop: As long as there is someone waiting, keep serving. If the shop is empty when you arrive, you do nothing.


💻 1. The Basic Syntax

DECLARE
   v_counter NUMBER := 1;
BEGIN
   -- 🚦 Check condition FIRST
   WHILE v_counter <= 5 LOOP
      DBMS_OUTPUT.PUT_LINE('Serving customer: ' || v_counter);
      v_counter := v_counter + 1; -- ⚙️ Must increment!
   END LOOP;
END;

🛡️ 2. Key Differences (Architect's Note)

  1. Basic Loop: Runs the code, THEN checks if it should exit. (Guaranteed at least 1 run).
  2. WHILE Loop: Checks the condition, THEN runs the code. (Can run 0 times).
  3. The NULL Trap: If the condition in a WHILE loop evaluates to NULL, Oracle treats it as FALSE and the loop ends immediately.

📊 Comparison Table

Feature Basic LOOP WHILE Loop
Check Time At the bottom 🏁 At the top 🚦
Minimum Runs 1 0
Use Case When you must run once When condition is unknown

📈 Learning Path