Sub topic 3
Counting with the Numeric FOR LOOP
This chapter assumes you know PL/SQL block structure, scalar variables, basic SQL SELECT and DML, and how to run a script with DBMS_OUTPUT enabled.
Counting with the Numeric FOR LOOP
The numeric FOR loop declares its own integer counter, runs the body once for each value in a range, and ends the counter after the last value. REVERSE makes the counter count down from the upper bound to the lower bound.
BEGIN
FOR i IN REVERSE 1..3 LOOP
DBMS_OUTPUT.PUT_LINE('Countdown: ' || i);
END LOOP;
END;
/This prints 3, 2, and 1. The counter exists only inside the loop. You cannot assign to it in the loop body, and the compiler rejects that.
Skipping Iterations and Leaving Nested Loops: CONTINUE and Labels
CONTINUE WHEN skips the rest of the current iteration when its condition is TRUE. A label, written as <<name>>, lets EXIT name a loop to leave, so you can exit an outer loop from an inner one.
BEGIN
<<outer>>
FOR i IN 1..3 LOOP
FOR j IN 1..3 LOOP
CONTINUE WHEN j = 2;
EXIT outer WHEN i = 2;
DBMS_OUTPUT.PUT_LINE(i || ',' || j);
END LOOP;
END LOOP outer;
END;
/This prints 1,1 and 1,3. The inner CONTINUE skips j = 2. When i reaches 2, EXIT outer stops both loops.
Looping Over Query Results with a Cursor FOR LOOP
A cursor FOR loop opens a query, fetches each row into a record, and closes the cursor when the loop ends. You do not write OPEN, FETCH, or CLOSE. The example assumes the Oracle HR sample schema.
BEGIN
FOR r IN (SELECT employee_id, last_name
FROM employees
WHERE department_id = 50
ORDER BY employee_id) LOOP
DBMS_OUTPUT.PUT_LINE(r.employee_id || ' ' || r.last_name);
END LOOP;
END;
/Read each column through the record, such as r.last_name.
Choosing the Right Control-Flow Construct
Start with the question each loop answers. The table summarizes the choice.
| Task | Construct |
|---|---|
| Repeat a known number of times | Numeric FOR LOOP |
| Repeat while a condition holds, tested before each pass | WHILE LOOP |
| Repeat until a condition inside the body is met | Basic LOOP with EXIT WHEN |
| Process each row of a query | Cursor FOR LOOP |
When a Loop Should Be a Single SQL Statement
A loop that runs one DML statement per row is slow. Each pass switches between the PL/SQL engine and the SQL engine. A single set-based statement does the same work in one pass. Prefer the single statement when SQL can express the logic.
UPDATE employees
SET salary = salary * 1.03
WHERE department_id = 50;Keep a loop only when each row needs procedural logic that SQL cannot express clearly.
Exercise
Inside a numeric FOR loop over 1..4 that prints i, which values print if the body starts with CONTINUE WHEN i = 3?
Show answer
1, 2, and 4. The value 3 is skipped.