Sub topic 6
Fetch loop patterns
A fetch loop is the code that repeats FETCH on an open explicit cursor until the cursor has no more rows. This chapter covers the two manual patterns, LOOP with EXIT WHEN and WHILE with a priming fetch. It also covers where the exit test belongs and the mistakes that follow when it is in the wrong place.
It assumes you can declare, open and close an explicit cursor, fetch into a %ROWTYPE record, and read %FOUND, %NOTFOUND, %ISOPEN and %ROWCOUNT. You should also know basic PL/SQL control flow and exception handling. The examples use the employees table from the Oracle HR sample schema.
What a fetch loop must do
Every manual fetch loop has to do four things:
- Fetch the next row into variables or a record.
- Test whether the fetch returned a row.
- Process the row only if it did.
- Repeat, then close the cursor once the loop is finished.
The patterns differ in where the test sits relative to the fetch. Oracle does not raise an error when a fetch finds no more rows. It sets %NOTFOUND to true and leaves the target variables unchanged. A loop that ignores the test never ends, or it processes the last row twice.
Pattern 1: LOOP with EXIT WHEN
This is the most common pattern. The loop is unconditional. The exit test comes immediately after the fetch and before any processing.
DECLARE
CURSOR c_emp IS
SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 50
ORDER BY last_name;
r_emp c_emp%ROWTYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO r_emp;
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(c_emp%ROWCOUNT || ' ' || r_emp.last_name);
END LOOP;
CLOSE c_emp;
END;
/The test is %NOTFOUND, not %FOUND, because EXIT WHEN leaves the loop when its condition is true. When the fetch fails, %NOTFOUND is true and the loop exits before the processing line runs.
%ROWCOUNT is the number of rows fetched so far. It works as a running row number inside the loop. After the loop it holds the total number of rows fetched, as long as the cursor is still open.
DECLARE
CURSOR c_emp IS
SELECT last_name FROM employees WHERE department_id = 50;
l_name employees.last_name%TYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO l_name;
EXIT WHEN c_emp%NOTFOUND;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Fetched ' || c_emp%ROWCOUNT || ' rows');
CLOSE c_emp;
END;
/Read %ROWCOUNT before CLOSE. After the cursor is closed, referencing any attribute raises ORA-01001, invalid cursor.
Pattern 2: WHILE with a priming fetch
The WHILE pattern tests the condition at the top of the loop, so a fetch must happen before the first test. That first fetch is the priming fetch. A second fetch sits at the bottom of the loop body to fetch the next row.
DECLARE
CURSOR c_emp IS
SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 50
ORDER BY last_name;
r_emp c_emp%ROWTYPE;
BEGIN
OPEN c_emp;
FETCH c_emp INTO r_emp;
WHILE c_emp%FOUND LOOP
DBMS_OUTPUT.PUT_LINE(r_emp.last_name || ': ' || r_emp.salary);
FETCH c_emp INTO r_emp;
END LOOP;
CLOSE c_emp;
END;
/This pattern uses %FOUND because WHILE continues while its condition is true. It handles an empty result set cleanly. If the priming fetch finds nothing, %FOUND is false and the body never runs.
The cost is two identical FETCH statements. If you change the select list or the target, you must change both, and forgetting the second fetch gives an infinite loop. Because of this, most code uses Pattern 1 instead. The WHILE form is useful when the loop condition combines the fetch result with other logic, such as a stop flag.
DECLARE
CURSOR c_emp IS
SELECT last_name, salary FROM employees ORDER BY salary DESC;
r_emp c_emp%ROWTYPE;
l_total NUMBER := 0;
BEGIN
OPEN c_emp;
FETCH c_emp INTO r_emp;
WHILE c_emp%FOUND AND l_total < 50000 LOOP
l_total := l_total + r_emp.salary;
DBMS_OUTPUT.PUT_LINE(r_emp.last_name || ' running total ' || l_total);
FETCH c_emp INTO r_emp;
END LOOP;
CLOSE c_emp;
END;
/The same stop condition works with Pattern 1. Use EXIT WHEN c_emp%NOTFOUND OR l_total >= 50000; after the fetch. Choose by readability.
Flow of the two patterns
Comparing the patterns
| Aspect | LOOP with EXIT WHEN | WHILE with priming fetch |
|---|---|---|
| Attribute tested | `%NOTFOUND` | `%FOUND` |
| FETCH statements | One | Two, kept in sync by hand |
| Empty result set | Exits on first test | Body never runs |
| Typical failure | Exit test placed after processing | Missing second fetch gives an infinite loop |
| Best when | Default choice | The loop condition mixes in other logic |
The classic bug: testing after processing
This version prints the last row twice:
DECLARE
CURSOR c_emp IS
SELECT last_name FROM employees WHERE department_id = 50;
l_name employees.last_name%TYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO l_name;
DBMS_OUTPUT.PUT_LINE(l_name); -- runs even after a failed fetch
EXIT WHEN c_emp%NOTFOUND;
END LOOP;
CLOSE c_emp;
END;
/On the final iteration the fetch finds no row, so l_name keeps the value from the previous row. The PUT_LINE then prints that stale value, and the loop exits afterward. The same bug on an empty result set processes a variable that was never assigned.
Attribute behavior you need to know
- Before the first fetch,
%FOUNDand%NOTFOUNDare both NULL, and%ROWCOUNTis 0. A test such asWHILE c_emp%FOUNDbefore the priming fetch would not enter the loop, because NULL is not true. - After a successful fetch,
%FOUNDis true and%NOTFOUNDis false. - After a fetch that finds no row,
%NOTFOUNDis true. Fetching again does not raise an error, and%ROWCOUNTstays at the number of rows already fetched. - Attributes always describe the most recent fetch on that cursor. Another cursor's fetch does not change them, so name the cursor in every test.
- Do not use an unqualified
SQL%NOTFOUNDin place ofc_emp%NOTFOUND. TheSQLattributes describe the most recent implicit cursor and do not track your explicit cursor.
Stopping early and the top-N pattern
You can leave a fetch loop at any time with EXIT WHEN. The row counter makes a "first N rows" loop simple:
DECLARE
CURSOR c_emp IS
SELECT last_name, salary FROM employees ORDER BY salary DESC;
r_emp c_emp%ROWTYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO r_emp;
EXIT WHEN c_emp%NOTFOUND OR c_emp%ROWCOUNT > 3;
DBMS_OUTPUT.PUT_LINE(c_emp%ROWCOUNT || '. ' || r_emp.last_name);
END LOOP;
CLOSE c_emp;
END;
/The loop fetches a fourth row only to find that %ROWCOUNT > 3. If the query is large, a FETCH FIRST 3 ROWS ONLY clause in the SQL itself avoids this extra work and lets the database stop sooner.
Closing the cursor when something goes wrong
An exception inside the loop skips the CLOSE. The cursor stays open until the block ends, and Oracle closes it when the cursor goes out of scope. A cursor declared in a package, or opened in a long-running session, can stay open much longer. Every open cursor counts against OPEN_CURSORS, so leaks can lead to ORA-01000, maximum open cursors exceeded.
Put a guarded close in the exception handler:
DECLARE
CURSOR c_emp IS
SELECT last_name, salary FROM employees WHERE department_id = 50;
r_emp c_emp%ROWTYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO r_emp;
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(r_emp.last_name || ': ' || (100000 / r_emp.salary));
END LOOP;
CLOSE c_emp;
EXCEPTION
WHEN OTHERS THEN
IF c_emp%ISOPEN THEN
CLOSE c_emp;
END IF;
RAISE;
END;
/Testing %ISOPEN first matters. Closing a cursor that is not open raises ORA-01001. The final RAISE passes the original error on, so the caller still sees the failure.
Common errors in fetch loops
| Error | Typical cause |
|---|---|
| ORA-06511: cursor already open | `OPEN` on a cursor that was not closed, often inside an outer loop |
| ORA-01001: invalid cursor | Fetching or reading an attribute after `CLOSE`, or closing twice |
| ORA-01002: fetch out of sequence | Fetching from a cursor after an error invalidated it, or after a commit on a `FOR UPDATE` cursor |
| ORA-01000: maximum open cursors exceeded | Cursors opened repeatedly and never closed |
| Last row appears twice | Exit test placed after the processing statements |
| Infinite loop | No exit test, or no second FETCH in a `WHILE` loop |
Fetch loops and BULK COLLECT
The patterns above fetch one row per FETCH. With BULK COLLECT ... LIMIT, one FETCH returns up to a batch of rows. The %NOTFOUND test is then unsafe. It becomes true when the last batch has fewer rows than the limit, so EXIT WHEN c%NOTFOUND placed right after the fetch skips the final partial batch. A later chapter covers the safe form, which tests the collection's COUNT instead.
Choosing between the patterns
Use LOOP with EXIT WHEN as your default. It has one fetch, one test and a clear place to put processing. Use WHILE when the loop's continuation condition combines the fetch result with other logic and you want that visible at the top. In both cases, test the cursor attributes immediately after the fetch. The cursor FOR loop, covered next, performs these steps for you. It is the better choice when you have no special need for manual control.
Exercise
The following loop is meant to print each last name in department 50 once, but the final name appears twice. What is wrong, and what is the fix? BEGIN ... OPEN cemp; LOOP FETCH cemp INTO lname; DBMSOUTPUT.PUTLINE(lname); EXIT WHEN cemp%NOTFOUND; END LOOP; CLOSE cemp; END;
Show answer
The exit test comes after the PUTLINE. When the fetch finds no more rows, lname keeps the last row's value, so it is printed again before the loop exits. Move EXIT WHEN cemp%NOTFOUND; so it directly follows the FETCH, before the PUTLINE.
Exercise
Rewrite a LOOP with EXIT WHEN c_emp%NOTFOUND as a WHILE loop. Which attribute do you test, and where do the FETCH statements go?
Show answer
Test c_emp%FOUND in the WHILE condition. Place one FETCH after OPEN, before the loop (the priming fetch). Place a second FETCH as the last statement in the loop body, after the row has been processed.