Iterative statements: Loop-End Loop, For-Loop, While Loop, Exit Loop, Continue

Iterative statements let your database code automatically repeat a set of SQL commands multiple times until a specific condition is met.

10 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Automating repetitive ticket updates

Imagine your manager at TicketDesk wants you to print an automated alert message for 10 pending tickets in a row. Would you manually write the DBMS_OUTPUT.PUT_LINE statement 10 separate times in your script? What if there were 1000 tickets tomorrow? Your code would become massive and unmanageable. You need a structural tool that can execute a single block of code repeatedly while automatically keeping track of how many records remain to be handled.

Theory

The Supermarket Scanner

Think of a billing counter at a supermarket. The cashier does not boot up a brand new computer program for every item in your shopping basket. Instead, they run one simple process: grab an item, pass it across the optical scanner, and add to the total price. They repeat this exact action loop over and over. When the basket runs completely empty, the loop breaks automatically and they finalize your bill.

Theory

Iterative Statements in Oracle Dialect

In Oracle PL/SQL, iterative statements are control mechanisms that execute a sequence of code statements multiple times. PL/SQL provides three main loop varieties: the basic loop (LOOP ... END LOOP), the conditional WHILE loop, and the counter-driven FOR loop. To fine-tune this repetition, you use loop controls: EXIT or EXIT WHEN to break out of a loop instantly, and CONTINUE or CONTINUE WHEN to skip the remaining code in the current iteration and jump straight to the next cycle.

At a glance

Operational profiles of the three primary Oracle PL/SQL iteration types

Loop StructureWhen Condition is CheckedBest Use Case
Basic LoopInside the body via explicit EXIT WHENWhen the loop body must run at least once
WHILE LoopAt the top before entering the loopWhen repeating depends on a changing condition
FOR LoopAt the top for a fixed index rangeWhen you know the exact iteration count in advance

Practical

Processing a Batch of Tickets Using Loops

-- Enable text rendering in the Oracle engine
SET SERVEROUTPUT ON;

DECLARE
  v_counter NUMBER := 1;
  v_max_tickets NUMBER := 3;
BEGIN
  DBMS_OUTPUT.PUT_LINE('=== Starting Basic Loop ===');
  LOOP
    DBMS_OUTPUT.PUT_LINE('Processing Ticket ID: ' || v_counter);
    v_counter := v_counter + 1;
    
    -- Explicit exit condition safely stops the execution
    EXIT WHEN v_counter > v_max_tickets;
  END LOOP;

  DBMS_OUTPUT.PUT_LINE('=== Starting FOR Loop Control ===');
  -- The loop index variable i is implicitly declared here
  FOR i IN 1..3 LOOP
    IF i = 2 THEN
      -- Skip processing for ticket 2 and proceed to next index
      CONTINUE;
    END IF;
    DBMS_OUTPUT.PUT_LINE('Handling Priority Index: ' || i);
  END LOOP;
END;
/

Copy and open Oracle FreeSQL
Oracle FreeSQL is a free online editor for Oracle SQL. The code is copied first: paste it there and run it.

Quiz

What is the correct syntax for defining a fixed numeric range inside an Oracle PL/SQL FOR loop statement?

  1. FOR i IN 1 TO 10 LOOP
  2. FOR i IN 1..10 LOOP
  3. FOR i = 1 TO 10 LOOP
  4. FOR i IN 1...10 LOOP
Show the answer

FOR i IN 1..10 LOOP

Oracle PL/SQL uses a double period operator (..) to denote an inclusive range between two integers inside a FOR loop. Keywords like TO or equal signs are invalid loop constraints in this language dialect and will trigger an immediate compilation failure during your lab exam.

Think first

Mental Challenge: The Execution Difference

What happens if a WHILE loop condition evaluates to FALSE on its very first check? Does the loop body execute at all? Figure out the execution pathway mentally before tapping.

Show the answer

The loop body will not execute a single time! A WHILE loop evaluates its entry condition at the very top before allowing the engine inside. If the statement evaluates to false immediately, the engine completely skips past the END LOOP statement, jumping straight to the subsequent program logic.

Watch out

The Dreaded Infinite Loop Nightmare

The most frequent error committed by BCA students in lab practicals is forgetting to increment the loop counter inside a basic LOOP. If you omit v_counter := v_counter + 1;, your counter remains stuck at its initial value forever. Because your EXIT WHEN clause can never become true, the database engine will consume critical memory processing an infinite cycle until the terminal locks up or the server crashes completely.

Theory

Cursor Navigation and Future Sync Routines

In production enterprise environments, loops are paired directly with cursors to walk through rows of live table records dynamically. You will utilize this pattern extensively next semester in your Sem 3 SQLite mobile database sync routines, where you will program a loop to check smartphone diagnostic signals and transmit local logs to the central backend master server one record at a time.

Summary

Key takeaways

  • Basic loops run indefinitely until stopped by an explicit exit condition statement.
  • WHILE loops test conditions at the entry boundary before executing any block statements.
  • FOR loops automate range progression safely using an implicitly declared numerical index.
  • The EXIT keyword completely terminates loop execution and jumps beyond the block boundary.
  • The CONTINUE modifier bypasses the current loop cycle to start the subsequent iteration directly.
  • Memory hook: Loop to repeat, exit to complete, count with dot-dot, skip with continue!

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from PL/SQL and Conditional Statements

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Iterative statements: Loop-End Loop, For-Loop, While Loop, Exit Loop, Continue · Mastering SQL - PL/SQL (SEC-02 option A) · Gri-Learn