Control Structures  «Prev  Next»

Lesson 5 FOR and WHILE loops
Objective Describe structure of FOR/WHILE loops.

FOR and WHILE loops in PL/SQL

Now that you have learned about the basic loop constructs, let us learn about the iterative loop constructs: FOR loops and WHILE loops.

FOR loop

A FOR loop iterates over a specified range of integers. The statements are executed once for each integer in range. The range is part of an iteration scheme, enclosed by FOR and LOOP.
The range is evaluated when the FOR loop is first entered and never reevaluated. After each iteration, the loop counter is incremented. The loop counter cannot be assigned values. The bounds of the loop range can be literals, variables, or expressions, but they must evaluate to integers. PL/SQL allows the loop range to be assigned dynamically at runtime.

Oracle For Loop
For i in 1..10 LOOP
  statement_1,.., statement_n;
END LOOP;
Example:
For i in 1..total_order LOOP
  inventory_count := inventory_count - 1;
END LOOP;

Oracle Database PL/SQL Programming

WHILE loop

The WHILE-LOOP statement associates a condition with sequence of statements enclosed by the keywords LOOP and END LOOP. Before each iteration of the loop, the condition is evaluated. If the condition evaluates to TRUE, the sequence of statements is executed, and the control resumes at the top of the loop. If the condition evaluates to FALSE or NULL, the loop is bypassed and the control passes to the next statement. The number of iterations depends on the condition and is unknown until the loop completes.

Oracle While Loop
WHILE condition1 is TRUE LOOP
  statement_1,..., statement_n;
END LOOP;
PL/SQL While Loop: A boolean condition will appear at the beginning of the PL/SQL block.

In the next lesson, you will learn about labels and the GOTO statement.