Sub topic 2
Implicit cursors: SQL%ROWCOUNT and friends
This chapter assumes you can write an anonymous PL/SQL block with DECLARE, BEGIN, EXCEPTION and END. It also assumes you know basic SQL DML, variables, IF statements and simple exception handling. By the end you will be able to read the outcome of any DML statement through the SQL cursor attributes. You will also know where those attributes can mislead you.
What an implicit cursor is
Every SQL statement that runs inside PL/SQL needs a cursor, a handle to the private memory area where Oracle parses and executes the statement. You manage that handle yourself only for explicit cursors, which later chapters cover. For everything else, Oracle opens and closes a cursor for you. This is an implicit cursor.
Implicit cursors are used for:
INSERT,UPDATE,DELETEandMERGESELECT ... INTOqueries that return a single row
You never declare, open or close these cursors. Oracle exposes information about the most recently executed one through a fixed name, SQL. You read its attributes by writing SQL% followed by the attribute name.
The four attributes
| Attribute | Type | Meaning after a DML statement |
|---|---|---|
| `SQL%ROWCOUNT` | integer | Number of rows the statement inserted, updated or deleted |
| `SQL%FOUND` | boolean | `TRUE` if at least one row was affected |
| `SQL%NOTFOUND` | boolean | `TRUE` if no row was affected |
| `SQL%ISOPEN` | boolean | Always `FALSE`, because Oracle closes the implicit cursor as soon as the statement finishes |
Before any SQL statement has run in the session, SQL%FOUND and SQL%NOTFOUND are NULL and SQL%ROWCOUNT is NULL. After the first statement runs, they hold real values.
Reading SQL%ROWCOUNT
The simplest use is reporting how many rows a DML statement touched.
BEGIN
UPDATE employees
SET salary = salary * 1.05
WHERE department_id = 50;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' rows updated');
ROLLBACK;
END;
/Run SET SERVEROUTPUT ON first in SQL*Plus or SQL Developer, or you will see nothing. The ROLLBACK at the end keeps the example from permanently changing salaries.
The count reflects what the statement did:
INSERT ... SELECTcounts the rows inserted.DELETEcounts the rows deleted.UPDATEcounts the rows matched by theWHEREclause, even if a row's new value equals its old value.MERGEcounts the rows inserted plus the rows updated (and deleted, if the statement has a delete clause).- A single-row
INSERT ... VALUESgives 1.
No rows affected is not an error
An UPDATE or DELETE that matches zero rows completes normally. It raises no exception. You detect the situation by testing the attribute.
DECLARE
l_dept_id employees.department_id%TYPE := 9999;
BEGIN
DELETE FROM employees
WHERE department_id = l_dept_id;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('No employees in department ' || l_dept_id);
ELSE
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' employees deleted');
END IF;
ROLLBACK;
END;
/SQL%FOUND and SQL%NOTFOUND are exact opposites after a DML statement, so use whichever reads better. Many programmers prefer SQL%ROWCOUNT = 0 when they also want to report the count.
The update-or-insert pattern
Because a zero-row update is silent, SQL%NOTFOUND is a common way to fall back to an insert.
DECLARE
l_id departments.department_id%TYPE := 280;
l_name departments.department_name%TYPE := 'Data Platform';
BEGIN
UPDATE departments
SET department_name = l_name
WHERE department_id = l_id;
IF SQL%NOTFOUND THEN
INSERT INTO departments (department_id, department_name)
VALUES (l_id, l_name);
DBMS_OUTPUT.PUT_LINE('Inserted');
ELSE
DBMS_OUTPUT.PUT_LINE('Updated');
END IF;
ROLLBACK;
END;
/This works, but two concurrent sessions can both see no row and both insert, so one of them fails with a unique-key error. A single MERGE statement is safer when concurrency matters.
SELECT INTO behaves differently
A SELECT ... INTO statement also uses an implicit cursor. Unlike DML, it signals "no rows" by raising an exception instead of leaving SQL%NOTFOUND for you to check.
- Zero rows raise
NO_DATA_FOUND. - More than one row raises
TOO_MANY_ROWS.
Checking SQL%NOTFOUND after a SELECT INTO is a common mistake. Execution never reaches the check when no row is found, because control has already jumped to the exception handler.
DECLARE
l_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = 99999;
DBMS_OUTPUT.PUT_LINE(l_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No such employee');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Query returned more than one row');
END;
/An aggregate query without GROUP BY always returns exactly one row, so SELECT COUNT(*) INTO ... never raises NO_DATA_FOUND. When the query does succeed, SQL%ROWCOUNT is 1. After TOO_MANY_ROWS, SQL%ROWCOUNT is also 1, because the fetch stops after the second row is detected. Do not use it to learn how many rows matched.
Gotchas
The attributes describe only the latest SQL statement
Each SQL statement overwrites the attributes. If you run another statement before reading them, you read the wrong values.
DECLARE
l_updated PLS_INTEGER;
l_deleted PLS_INTEGER;
BEGIN
UPDATE employees SET commission_pct = 0.1 WHERE department_id = 80;
l_updated := SQL%ROWCOUNT;
DELETE FROM job_history WHERE department_id = 80;
l_deleted := SQL%ROWCOUNT;
DBMS_OUTPUT.PUT_LINE('Updated: ' || l_updated || ', deleted: ' || l_deleted);
ROLLBACK;
END;
/Copy the value into a variable on the line right after the statement. This habit also protects you when someone later inserts a logging INSERT between the DML and the check.
SQL%ISOPEN is useless for implicit cursors
SQL%ISOPEN exists so that code can treat the SQL cursor like other cursors. It is always FALSE because the cursor is already closed when your code regains control. Tests against it never change the result.
The attributes are for PL/SQL, not SQL
You can use SQL%ROWCOUNT in procedural statements such as assignments, IF conditions and calls to DBMS_OUTPUT. You cannot put it inside a SQL statement. For example, INSERT INTO log_table VALUES (SQL%ROWCOUNT) fails. Assign the value to a variable first, then insert the variable.
Rollback does not reset the count
ROLLBACK undoes the changes but does not alter what SQL%ROWCOUNT reports about the statement that ran. The attribute tells you what the statement did, not what is currently committed or visible.
Bulk operations
FORALL statements run the same DML many times from one collection. After a FORALL, SQL%ROWCOUNT gives the total across all iterations. SQL%BULK_ROWCOUNT(i) gives the count for each individual iteration. This chapter covers only the plain scalar attributes, and the bulk-processing chapter returns to FORALL.
Cursor FOR loops are not implicit cursors
A loop such as FOR r IN (SELECT ...) LOOP uses a cursor that Oracle manages for you, but it is not the SQL cursor. The SQL% attributes do not describe the loop. Later chapters show the attributes that do, which are the ones that belong to explicit cursors.
When to use which check
| Situation | What to use |
|---|---|
| Report how many rows a DML statement changed | `SQL%ROWCOUNT`, copied to a variable |
| Fall back when `UPDATE` or `DELETE` matched nothing | `SQL%NOTFOUND` (or `SQL%ROWCOUNT = 0`) |
| Single-row query might find nothing | `NO_DATA_FOUND` handler |
| Single-row query might find several | `TOO_MANY_ROWS` handler |
| Total rows across a `FORALL` | `SQL%ROWCOUNT` right after the statement |
Exercise
A block runs UPDATE employees SET salary = salary WHERE department_id = 10; and then DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT);. Department 10 has one employee, and every salary is left unchanged. What is printed, and why?
Show answer
It prints 1. SQL%ROWCOUNT counts the rows the WHERE clause matched and the statement processed, not the rows whose values actually changed.
Exercise
A programmer writes SELECT last_name INTO l_name FROM employees WHERE employee_id = 99999; followed by IF SQL%NOTFOUND THEN ... END IF;, with no exception handler. The ID does not exist. What happens, and how should the code be fixed?
Show answer
Oracle raises NO_DATA_FOUND at the SELECT INTO, so the IF is never reached and the exception propagates out of the block. Fix it by adding an EXCEPTION WHEN NO_DATA_FOUND THEN ... handler (or wrapping the query in an inner block) and removing the SQL%NOTFOUND test.
Exercise
Write a block that deletes every row from job_history for employee 999, prints a different message depending on whether any rows were deleted, and keeps the row count after a later statement runs.
Show answer
DECLARE ldeleted PLSINTEGER; BEGIN DELETE FROM jobhistory WHERE employeeid = 999; ldeleted := SQL%ROWCOUNT; IF ldeleted = 0 THEN DBMSOUTPUT.PUTLINE('Nothing to delete'); ELSE DBMSOUTPUT.PUTLINE(l_deleted || ' rows deleted'); END IF; ROLLBACK; END; /