Sub topic 4
Cursor attributes
Every cursor reports its own state through four attributes: %ISOPEN, %FOUND, %NOTFOUND and %ROWCOUNT. This chapter covers what each one returns at each point in a cursor's life, how the implicit cursor SQL differs from an explicit cursor, and the mistakes that cause ORA-01001 and silent logic bugs.
It assumes you can write an anonymous block, declare and open an explicit cursor, and catch an exception. You should also know the OPEN, FETCH and CLOSE steps from the previous chapter.
The four attributes
You write an attribute after the cursor name, with no space: c_emp%FOUND. For the implicit cursor, the name is SQL: SQL%FOUND.
| Attribute | Type | Meaning |
|---|---|---|
| `%ISOPEN` | BOOLEAN | TRUE while the cursor is open |
| `%FOUND` | BOOLEAN | TRUE if the last fetch returned a row (or the last DML touched a row) |
| `%NOTFOUND` | BOOLEAN | The logical opposite of `%FOUND`, except where `%FOUND` is NULL |
| `%ROWCOUNT` | INTEGER | Number of rows fetched so far (or rows affected by the last DML) |
Values across the explicit cursor lifecycle
The values depend on where the cursor is in its lifecycle. Two details surprise people. Before the first fetch, %FOUND and %NOTFOUND are NULL, not FALSE. And a fetch that returns no row leaves %ROWCOUNT unchanged.
| State | `%ISOPEN` | `%FOUND` | `%NOTFOUND` | `%ROWCOUNT` |
|---|---|---|---|---|
| Declared, not opened | FALSE | error | error | error |
| Opened, no fetch yet | TRUE | NULL | NULL | 0 |
| Last fetch returned a row | TRUE | TRUE | FALSE | n |
| Last fetch returned no row | TRUE | FALSE | TRUE | n (unchanged) |
| Closed | FALSE | error | error | error |
"Error" means PL/SQL raises INVALID_CURSOR (ORA-01001). Only %ISOPEN is safe to test on a cursor that is not open.
Watching the values change
This block prints every attribute after each step. The helper function b converts a BOOLEAN to text, because DBMS_OUTPUT.PUT_LINE cannot print a BOOLEAN and a NULL would otherwise vanish.
SET SERVEROUTPUT ON
DECLARE
CURSOR c_emp IS
SELECT last_name
FROM employees
WHERE department_id = 50
ORDER BY last_name;
l_name employees.last_name%TYPE;
FUNCTION b(p_val BOOLEAN) RETURN VARCHAR2 IS
BEGIN
RETURN CASE WHEN p_val THEN 'TRUE'
WHEN NOT p_val THEN 'FALSE'
ELSE 'NULL' END;
END b;
PROCEDURE show(p_step VARCHAR2) IS
BEGIN
DBMS_OUTPUT.PUT_LINE(RPAD(p_step, 12)
|| ' found=' || b(c_emp%FOUND)
|| ' notfound=' || b(c_emp%NOTFOUND)
|| ' rowcount=' || c_emp%ROWCOUNT);
END show;
BEGIN
DBMS_OUTPUT.PUT_LINE('before open: isopen=' || b(c_emp%ISOPEN));
OPEN c_emp;
show('after open');
LOOP
FETCH c_emp INTO l_name;
show('fetch');
EXIT WHEN c_emp%NOTFOUND;
END LOOP;
CLOSE c_emp;
DBMS_OUTPUT.PUT_LINE('after close: isopen=' || b(c_emp%ISOPEN));
END;
/The output starts with found=NULL notfound=NULL rowcount=0 right after the open. The last fetch line shows notfound=TRUE with the same rowcount as the line before it.
Where to test each attribute
Test %NOTFOUND immediately after the FETCH, before you use the fetched variables. When a fetch returns no row, the target variables keep their previous values. If you process them before the test, the last row is handled twice.
Test %NOTFOUND rather than %FOUND in a basic loop, because EXIT WHEN c_emp%NOTFOUND is true only when the fetch truly found nothing. If you use %FOUND, you need a priming fetch before a WHILE loop, as below.
DECLARE
CURSOR c_emp IS
SELECT last_name, salary FROM employees WHERE department_id = 50;
r_emp c_emp%ROWTYPE;
BEGIN
OPEN c_emp;
FETCH c_emp INTO r_emp; -- priming fetch
WHILE c_emp%FOUND LOOP
DBMS_OUTPUT.PUT_LINE(r_emp.last_name);
FETCH c_emp INTO r_emp; -- fetch again at the end of the body
END LOOP;
DBMS_OUTPUT.PUT_LINE(c_emp%ROWCOUNT || ' rows fetched');
CLOSE c_emp;
END;
/If the query returns no rows, the priming fetch sets %FOUND to FALSE and the loop body never runs. You get no error and %ROWCOUNT is 0, which lets you tell an empty result from a populated one after the loop.
%ISOPEN as a guard
%ISOPEN is the one attribute that never raises an error, so use it to avoid two errors:
- Opening a cursor that is already open raises
ORA-06511: CURSOR_ALREADY_OPEN. - Closing a cursor that is not open raises
INVALID_CURSOR.
The usual use is in an exception handler, so that an error in the middle of a loop does not leave the cursor open:
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;
DBMS_OUTPUT.PUT_LINE(r_emp.employee_id || ': ' || r_emp.salary);
END LOOP;
CLOSE c_emp;
EXCEPTION
WHEN OTHERS THEN
IF c_emp%ISOPEN THEN
CLOSE c_emp;
END IF;
RAISE;
END;
/The RAISE at the end re-raises the original error after the cleanup, so the caller still sees the failure.
Using %ROWCOUNT inside a loop
%ROWCOUNT is a running counter, so you can use it to number rows or stop early. With a named cursor in a cursor FOR loop, it works inside the loop body:
DECLARE
CURSOR c_emp IS
SELECT last_name, salary
FROM employees
ORDER BY salary DESC;
BEGIN
FOR r IN c_emp LOOP
EXIT WHEN c_emp%ROWCOUNT > 5;
DBMS_OUTPUT.PUT_LINE(c_emp%ROWCOUNT || '. ' || r.last_name);
END LOOP;
DBMS_OUTPUT.PUT_LINE('isopen after loop: '
|| CASE WHEN c_emp%ISOPEN THEN 'TRUE' ELSE 'FALSE' END);
BEGIN
DBMS_OUTPUT.PUT_LINE(c_emp%ROWCOUNT);
EXCEPTION
WHEN INVALID_CURSOR THEN
DBMS_OUTPUT.PUT_LINE('cannot read ROWCOUNT: cursor is closed');
END;
END;
/The EXIT WHEN runs after the sixth row is fetched, so the loop prints five rows. The loop closes the cursor when it ends, so any attribute except %ISOPEN raises INVALID_CURSOR afterwards. If you need the final count after a cursor FOR loop, copy %ROWCOUNT into a variable inside the loop on every iteration.
A cursor FOR loop over an inline query has no cursor name, so you cannot reference its attributes at all. Count rows with your own variable in that case.
The implicit cursor: SQL%
Oracle runs every DML statement and every SELECT ... INTO through an implicit cursor named SQL. You never open or close it, and its attributes always describe the most recently executed SQL statement.
| Attribute | Behavior for the implicit cursor |
|---|---|
| `SQL%ISOPEN` | Always FALSE, because Oracle closes the cursor when the statement finishes |
| `SQL%FOUND` | TRUE if an INSERT, UPDATE or DELETE affected at least one row, or a SELECT INTO returned a row. NULL if no SQL statement has run yet. |
| `SQL%NOTFOUND` | The opposite of `SQL%FOUND` |
| `SQL%ROWCOUNT` | Rows affected by the last DML statement, or 0 if none |
Because the attributes describe only the last statement, read them straight after the statement you care about. Copy the value into a variable if other SQL runs before you use it:
DECLARE
l_updated PLS_INTEGER;
BEGIN
UPDATE employees
SET salary = salary * 1.05
WHERE department_id = 50;
l_updated := SQL%ROWCOUNT;
UPDATE employees
SET salary = salary
WHERE department_id = 9999;
DBMS_OUTPUT.PUT_LINE('first update: ' || l_updated);
DBMS_OUTPUT.PUT_LINE('second update: ' || SQL%ROWCOUNT);
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('second update matched no rows');
END IF;
ROLLBACK;
END;
/An UPDATE or DELETE that matches no rows is not an error, so SQL%NOTFOUND or SQL%ROWCOUNT = 0 is how you detect it.
SELECT INTO behaves differently
A SELECT ... INTO that finds no row raises NO_DATA_FOUND immediately, so your IF SQL%NOTFOUND test after it never runs. Handle the exception instead:
DECLARE
l_sal employees.salary%TYPE;
BEGIN
SELECT salary INTO l_sal FROM employees WHERE employee_id = -1;
DBMS_OUTPUT.PUT_LINE('found: ' || l_sal);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('no row, rowcount=' || SQL%ROWCOUNT);
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('more than one row, rowcount=' || SQL%ROWCOUNT);
END;
/For NO_DATA_FOUND, SQL%ROWCOUNT is 0. For TOO_MANY_ROWS, it is 1, because Oracle fetched one row before it detected the second.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ORA-01001: invalid cursor` | Attribute read before `OPEN`, after `CLOSE`, or after a cursor FOR loop ended | Read the attribute while the cursor is open, or copy the value to a variable |
| `ORA-06511: cursor already open` | `OPEN` on an open cursor, often after an earlier error skipped `CLOSE` | Test `%ISOPEN` first, and close in the exception handler |
| Last row processed twice | Code that uses fetched variables runs before the `%NOTFOUND` test | Put `EXIT WHEN c%NOTFOUND` straight after `FETCH` |
| Wrong `SQL%ROWCOUNT` | Another statement ran between the DML and the read | Copy it into a variable straight after the DML |
| `IF c%FOUND` is never true before the first fetch | `%FOUND` is NULL until a fetch happens | Fetch first, then test |
Exercise
An explicit cursor c has just been opened and no FETCH has run. What do c%FOUND, c%NOTFOUND and c%ROWCOUNT return, and what does c%ROWCOUNT return after a FETCH that finds no row, following 7 successful fetches?
Show answer
Right after OPEN, c%FOUND and c%NOTFOUND are NULL and c%ROWCOUNT is 0. After 7 successful fetches and then a fetch that finds no row, c%FOUND is FALSE, c%NOTFOUND is TRUE and c%ROWCOUNT is still 7, because a fetch that returns no row does not increment it.
Exercise
A block runs DELETE FROM employees WHERE department_id = 9999; followed by INSERT INTO job_history ... and then reads SQL%ROWCOUNT to report how many employees were deleted. Why is the report wrong, and how do you fix it?
Show answer
SQL%ROWCOUNT describes only the most recently executed SQL statement, so after the INSERT it reports the INSERT's row count. Fix it by assigning SQL%ROWCOUNT to a variable (for example l_deleted := SQL%ROWCOUNT;) immediately after the DELETE, and report that variable.
Exercise
Why does IF SQL%NOTFOUND THEN ... placed after SELECT salary INTO l_sal FROM employees WHERE employee_id = -1; never run, and what should you use to handle the missing row?
Show answer
A SELECT INTO that returns no row raises NO_DATA_FOUND, so control jumps to the exception section before the IF is reached. Handle it with WHEN NO_DATA_FOUND THEN ... in the exception section, or wrap the SELECT in its own inner block.