Skip to main 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

FeatureBasic LOOPWHILE Loop
Check TimeAt the bottom 🏁At the top 🚦
Minimum Runs10
Use CaseWhen you must run onceWhen condition is unknown

📈 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