Sub topic 13
Common cursor errors and closing cursors
This chapter covers the errors that explicit cursors and cursor FOR loops produce, and how to close cursors so they cannot leak. It assumes you can write an anonymous PL/SQL block with a DECLARE, BEGIN, EXCEPTION and END section. It also assumes you know the cursor lifecycle (declare, open, fetch, close), the four cursor attributes, and the basics of exception handling. The examples use the employees table from the HR sample schema.
Why cursor errors happen
Most cursor errors come from a mismatch between what the code assumes about a cursor's state and what the state actually is. A cursor is either open or closed. Every error in this chapter is an operation that is not allowed in the cursor's current state, or an operation that leaves too many cursors open.
The errors you will meet most often
| Error | Predefined exception | Typical cause |
|---|---|---|
| ORA-06511 | `CURSOR_ALREADY_OPEN` | `OPEN` on a cursor that is already open |
| ORA-01001 | `INVALID_CURSOR` | `FETCH` or `CLOSE` on a cursor that is not open, or reading `%ROWCOUNT` after `CLOSE` |
| ORA-01002 | none | `FETCH` out of sequence, usually after a `COMMIT` inside a `FOR UPDATE` loop |
| ORA-01000 | none | The session reached the `OPEN_CURSORS` limit because cursors were never closed |
| ORA-00054 | none | `FOR UPDATE NOWAIT` found a row locked by another session |
| ORA-01422 | `TOO_MANY_ROWS` | `SELECT INTO` matched more than one row |
| ORA-01403 | `NO_DATA_FOUND` | `SELECT INTO` matched no rows |
The last two belong to implicit cursors, which are covered below because they are easy to confuse with explicit cursor behavior.
ORA-06511: opening a cursor twice
An explicit cursor cannot be opened again until it is closed. This usually happens when an OPEN sits inside a loop or a procedure that runs more than once, and the matching CLOSE is skipped on one path.
DECLARE
CURSOR c_emp IS
SELECT employee_id FROM employees WHERE department_id = 50;
BEGIN
OPEN c_emp;
OPEN c_emp; -- raises ORA-06511
EXCEPTION
WHEN CURSOR_ALREADY_OPEN THEN
DBMS_OUTPUT.PUT_LINE('Already open: ' || SQLERRM);
IF c_emp%ISOPEN THEN
CLOSE c_emp;
END IF;
END;
/Guarding the OPEN with IF NOT c_emp%ISOPEN THEN hides the bug instead of fixing it. If the cursor is already open, the row position may not be where you expect. Fix the control flow so that every path closes the cursor.
ORA-01001: using a cursor that is not open
FETCH and CLOSE both raise INVALID_CURSOR when the cursor is closed. The same exception appears if you read c_emp%ROWCOUNT after CLOSE c_emp. Read %ROWCOUNT into a variable before closing if you need the value afterward.
DECLARE
CURSOR c_emp IS
SELECT employee_id FROM employees WHERE department_id = 50;
r_emp c_emp%ROWTYPE;
l_count PLS_INTEGER;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO r_emp;
EXIT WHEN c_emp%NOTFOUND;
END LOOP;
l_count := c_emp%ROWCOUNT; -- read before CLOSE
CLOSE c_emp;
DBMS_OUTPUT.PUT_LINE(l_count || ' rows fetched');
END;
/Inside a cursor FOR loop, the cursor is open only between LOOP and END LOOP. Referencing c_emp%ROWCOUNT or c_emp%ISOPEN after the loop is legal, but the cursor is already closed, so %ISOPEN is FALSE and %ROWCOUNT raises INVALID_CURSOR.
Closing cursors when an exception occurs
If an exception interrupts a manual OPEN/FETCH/CLOSE sequence, the CLOSE statement is never reached. Put a cleanup step in the exception section and test %ISOPEN first, so that you do not trigger ORA-01001 while handling the original error.
DECLARE
CURSOR c_emp IS
SELECT employee_id, 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;
IF r_emp.salary IS NULL THEN
RAISE_APPLICATION_ERROR(-20001,
'Missing salary for employee ' || r_emp.employee_id);
END IF;
END LOOP;
CLOSE c_emp;
EXCEPTION
WHEN OTHERS THEN
IF c_emp%ISOPEN THEN
CLOSE c_emp;
END IF;
RAISE;
END;
/The handler closes the cursor and then re-raises the original error with RAISE, so the caller still sees the real cause.
What Oracle closes for you, and what it does not
- A cursor FOR loop closes its cursor when the loop ends normally, when it exits with
EXIT, and when an exception leaves it. - A cursor declared in a block or subprogram is local to it. When the block ends, PL/SQL can release it, but you should not depend on that. An explicit
CLOSEstates your intent and frees the resources sooner. - A cursor declared at package level keeps its state for the whole session. If you open it and do not close it, it stays open until you close it or the session ends. This is the most common source of cursor leaks in PL/SQL.
- A
SYS_REFCURSORreturned to a client application must be closed by the client. The PL/SQL code that opened it has handed over the responsibility.
ORA-01000: maximum open cursors exceeded
Each session may hold only as many open cursors as the OPEN_CURSORS initialization parameter allows. When cursors are opened and never closed, the session reaches that limit and the next OPEN raises ORA-01000.
Raising OPEN_CURSORS treats the symptom. First find which sessions hold many cursors and what SQL they hold. With the privilege to query the dynamic performance views, these two queries help:
SELECT value AS open_cursors_limit
FROM v$parameter
WHERE name = 'open_cursors';
SELECT sid, COUNT(*) AS open_cnt
FROM v$open_cursor
GROUP BY sid
ORDER BY open_cnt DESC
FETCH FIRST 10 ROWS ONLY;Then look for OPEN statements without a matching CLOSE on every path, package-level cursors, DBMS_SQL cursors that were not closed, and client code that does not close the result sets it receives.
ORA-01002: fetch out of sequence
A cursor declared with FOR UPDATE holds row locks until the transaction ends. A COMMIT or ROLLBACK releases those locks, and the cursor can no longer continue. The next fetch raises ORA-01002.
DECLARE
CURSOR c_emp IS
SELECT employee_id, salary
FROM employees
WHERE department_id = 50
FOR UPDATE OF salary;
BEGIN
FOR r IN c_emp LOOP
UPDATE employees
SET salary = r.salary * 1.05
WHERE CURRENT OF c_emp;
COMMIT; -- releases the locks; the next fetch fails
END LOOP;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
ROLLBACK;
END;
/Move the COMMIT after END LOOP, as in the earlier FOR UPDATE example. If the transaction is too large to keep open, fetch the keys in batches with BULK COLLECT ... LIMIT and commit between batches. Do not use FOR UPDATE for that pattern.
ORA-00054: rows locked by another session
Plain FOR UPDATE waits indefinitely for locked rows. NOWAIT raises ORA-00054 immediately instead. This error has no predefined PL/SQL name, so associate one with PRAGMA EXCEPTION_INIT.
DECLARE
e_locked EXCEPTION;
PRAGMA EXCEPTION_INIT(e_locked, -54);
CURSOR c_emp IS
SELECT employee_id, salary
FROM employees
WHERE department_id = 50
FOR UPDATE OF salary NOWAIT;
BEGIN
FOR r IN c_emp LOOP
UPDATE employees
SET salary = r.salary * 1.05
WHERE CURRENT OF c_emp;
END LOOP;
COMMIT;
EXCEPTION
WHEN e_locked THEN
ROLLBACK;
DBMS_OUTPUT.PUT_LINE('Rows are locked by another session; try again later.');
END;
/FOR UPDATE WAIT 5 is a middle option. It waits up to five seconds and then raises the same error.
Implicit cursor errors: SELECT INTO
SELECT ... INTO uses an implicit cursor and requires exactly one row. Zero rows raise NO_DATA_FOUND, and two or more raise TOO_MANY_ROWS. This differs from DML statements, where zero affected rows are reported only through SQL%NOTFOUND or SQL%ROWCOUNT and raise no exception.
DECLARE
l_salary employees.salary%TYPE;
BEGIN
SELECT salary
INTO l_salary
FROM employees
WHERE department_id = 50; -- many rows match
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Query returned more than one row');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Query returned no rows');
END;
/If you expect zero, one or many rows, do not use SELECT INTO. Use a cursor FOR loop, or a cursor with FETCH and a %NOTFOUND test. Both treat an empty result as normal.
Logic mistakes that raise no error
- Testing
%NOTFOUNDbefore the first fetch. The attribute isNULLuntil a fetch has run, so the test neither exits nor continues in a useful way. Always test it immediately afterFETCH. - Processing before the exit test. Put
EXIT WHEN c%NOTFOUNDdirectly afterFETCH. If you process the record first, the last fetch, which returns no row, is processed with stale values. - Testing
%NOTFOUNDwithBULK COLLECT ... LIMIT. The last batch may be smaller than the limit, so%NOTFOUNDbecomes true while the collection still holds rows. Testl_emps.COUNT = 0instead, as in the batch-fetching example earlier. - Referring to the cursor FOR loop record outside the loop. The record exists only inside the loop. Copy the values you need into variables declared in the outer block.
A review checklist
- Does every
OPENhave aCLOSEon every path, including exception paths? - Could a cursor FOR loop replace the manual
OPEN/FETCH/CLOSEcode? - Is any cursor declared at package level, and who closes it?
- Does a
COMMITorROLLBACKsit inside a loop over aFOR UPDATEcursor? - Does every
SELECT INTOhave handlers forNO_DATA_FOUNDandTOO_MANY_ROWS, or can it be rewritten as a loop? - Does code that returns a
SYS_REFCURSORtell its caller to close it?
Exercise
A procedure uses a manual cursor loop with OPEN, FETCH and CLOSE. When a row contains bad data, the procedure raises an application error. The next call to the procedure, in the same session, fails with ORA-06511. The cursor is declared in a package body. What is the cause, and what are two ways to fix it?
Show answer
The exception skipped the CLOSE statement. Because the cursor is declared at package level, it stays open for the rest of the session, so the next OPEN raises ORA-06511 (CURSORALREADYOPEN). One fix is to add an exception handler that closes the cursor when c%ISOPEN is true and then re-raises the error with RAISE. The other is to declare the cursor locally and use a cursor FOR loop, which closes it automatically, even when an exception leaves the loop.
Exercise
A loop updates each row with WHERE CURRENT OF and issues a COMMIT after every row. It fails on the second iteration with ORA-01002. Why does it fail, and how would you restructure it if the transaction becomes too large to hold open?
Show answer
The cursor was declared FOR UPDATE, so it holds row locks. The COMMIT ends the transaction and releases the locks, and the cursor cannot continue, so the next fetch is out of sequence. If the transaction is too large, drop FOR UPDATE and WHERE CURRENT OF. Fetch the keys in batches with BULK COLLECT and LIMIT, update the rows by key, and commit between batches.
Exercise
Why is SELECT INTO a poor choice when a query may return zero, one or many rows, and what should you use instead?
Show answer
SELECT INTO raises NODATAFOUND for zero rows and TOOMANYROWS for more than one row, so every other outcome becomes an exception. A cursor FOR loop, or a cursor with FETCH and a %NOTFOUND test, handles all three cases without raising an exception.