Sub topic 14
Choosing the right technique
This chapter assumes you know the cursor lifecycle (OPEN, FETCH, CLOSE), the cursor attributes, and the cursor FOR loop, including the inline-query form. It also assumes you have met parameters, FOR UPDATE, SYS_REFCURSOR and BULK COLLECT ... LIMIT. Here you decide which of these to use for a given job.
Start with the question "Do I need a loop at all?"
PL/SQL runs inside the database, but each SQL statement still passes between the PL/SQL engine and the SQL engine. This is called a context switch. A loop that runs one UPDATE per fetched row pays that cost once per row. A single SQL statement pays it once.
This loop works but is the wrong tool:
BEGIN
FOR r IN (SELECT employee_id, salary
FROM employees
WHERE department_id = 50)
LOOP
UPDATE employees
SET salary = r.salary * 1.05
WHERE employee_id = r.employee_id;
END LOOP;
COMMIT;
END;
/It does the same work as this statement:
BEGIN
UPDATE employees
SET salary = salary * 1.05
WHERE department_id = 50;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' rows updated');
COMMIT;
END;
/The single statement is shorter and faster. It also holds locks for less time, and the optimizer can pick one plan for the whole set. Use it whenever the change can be written as INSERT ... SELECT, UPDATE, DELETE or MERGE. The SQL%ROWCOUNT attribute gives you the row count without a cursor.
When row-by-row processing is justified
Use a cursor when each row needs its own decision or action that SQL cannot express. Common cases:
- Calling a procedure for each row, especially one that has side effects.
- Branching logic with several outcomes per row, such as different error handling for different rows.
- Building a report line by line.
- Handling each row's failure separately, for example catching an exception per row and logging it.
Even then, try to push as much work as possible into the query itself (joins, filters, aggregates, analytic functions) so the loop receives only the rows it needs.
Comparing the techniques
| Technique | Best for | Main cost or risk |
|---|---|---|
| Single SQL statement | Any set-based change | Cannot run arbitrary per-row logic |
| Cursor FOR loop (named or inline) | Per-row logic over a moderate result set | Row-at-a-time DML inside it is slow on large sets |
| Explicit `OPEN`/`FETCH`/`CLOSE` | Control over when to stop, or fetching into separate variables | You must close it yourself, and mistakes leak cursors |
| `FOR UPDATE` with `WHERE CURRENT OF` | Updating the row you just fetched while holding its lock | Locks last until commit or rollback; no commit inside the loop |
| `SYS_REFCURSOR` | Queries chosen at run time, or returning a result set to a caller | The consumer must fetch and close it |
| `BULK COLLECT` with `LIMIT` | Large volumes, batch DML with `FORALL` | More code; memory use depends on the limit |
The cursor FOR loop is the default
If you need a loop, start with a cursor FOR loop. It opens, fetches and closes for you, so it cannot leak a cursor or forget EXIT WHEN. It also declares the record for you.
BEGIN
FOR r IN (SELECT last_name, salary
FROM employees
WHERE department_id = 50
ORDER BY last_name)
LOOP
IF r.salary >= 5000 THEN
DBMS_OUTPUT.PUT_LINE(r.last_name || ': senior band');
ELSE
DBMS_OUTPUT.PUT_LINE(r.last_name || ': standard band');
END IF;
END LOOP;
END;
/With the default optimization level (PLSQL_OPTIMIZE_LEVEL of 2 or higher), the compiler already fetches rows from a cursor FOR loop in batches of 100 behind the scenes. For read-only loops you often get most of the benefit of BULK COLLECT without writing any extra code. That optimization applies to the fetch only. It does not batch DML statements you run inside the loop.
Choose a named cursor over an inline query when you reuse the same query in several places or need parameters. Choose the inline form when the query is used once and short.
When to move to BULK COLLECT with LIMIT
Move to bulk processing when the loop body issues DML for every row and the row count is large. Fetch a batch into collections, then send the whole batch to SQL with FORALL. That turns thousands of context switches into a few.
This example logs a proposed raise. In real code you would write this particular insert as one INSERT ... SELECT. The pattern pays off when the batch step involves per-row computation that SQL cannot do.
CREATE TABLE emp_salary_log (
employee_id NUMBER,
old_salary NUMBER,
new_salary NUMBER
);
DECLARE
CURSOR c_emp IS
SELECT employee_id, salary FROM employees;
TYPE t_id_tab IS TABLE OF employees.employee_id%TYPE;
TYPE t_sal_tab IS TABLE OF employees.salary%TYPE;
l_ids t_id_tab;
l_sals t_sal_tab;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp BULK COLLECT INTO l_ids, l_sals LIMIT 500;
EXIT WHEN l_ids.COUNT = 0;
FORALL i IN 1 .. l_ids.COUNT
INSERT INTO emp_salary_log (employee_id, old_salary, new_salary)
VALUES (l_ids(i), l_sals(i), l_sals(i) * 1.05);
END LOOP;
CLOSE c_emp;
COMMIT;
END;
/Always use LIMIT. A bare BULK COLLECT INTO loads the whole result set into session memory (PGA), which can fail or slow the whole server when the table grows. A limit of 100 to 1000 is a common starting point. Measure before tuning it.
The end-of-loop trap
With LIMIT, the final fetch usually returns fewer rows than the limit, and %NOTFOUND becomes true on that fetch. If you write EXIT WHEN c_emp%NOTFOUND right after the fetch, you skip those last rows. Test l_ids.COUNT = 0 instead, as the example does. If you must use %NOTFOUND, place it after the processing code.
Locking: FOR UPDATE and WHERE CURRENT OF
Use FOR UPDATE when you read a row and then change it based on what you read, and no other session should change it in between. Add NOWAIT (or WAIT n) so you do not hang on a row another session holds.
Two gotchas matter in practice:
- A
COMMITorROLLBACKinside aFOR UPDATEloop releases the locks. Fetching again afterward can raiseORA-01002: fetch out of sequence. Commit after the loop ends. WHERE CURRENT OFworks only with a cursor declaredFOR UPDATE. If the query joins several tables,FOR UPDATE OF columnlimits locking to the table that owns that column.
If the update does not depend on a row-level read, a single UPDATE is simpler and locks the same rows.
REF CURSORs: for flexibility and hand-off
A static cursor's query is fixed when you compile. Use SYS_REFCURSOR when either of these is true:
- The query text or its shape is chosen at run time, for example different filters depending on input.
- A function or procedure must return a result set to a caller, such as a client application or another program unit.
A SYS_REFCURSOR cannot be used in a cursor FOR loop. You must fetch it with FETCH and close it. Whoever receives the cursor owns the closing. Decide that in your design and document it.
Decision flow
Cleanup and error habits
- Prefer the cursor FOR loop so you never have to close a cursor yourself. It also closes the cursor if an exception leaves the loop.
- With an explicit cursor, close it in the exception handler too, after checking
%ISOPEN. Otherwise you can hitORA-01000: maximum open cursors exceededover time. - Do not rely on
%ROWCOUNTor%FOUNDof an explicit cursor before the first fetch. They are not yet set. SQL%attributes refer to the most recent DML statement. Read them immediately, before running another statement.- Do not use a loop just to count rows.
SELECT COUNT(*)does that in one statement.
Summary of rules
- Prefer one SQL statement over any loop.
- If you must loop, use a cursor FOR loop.
- Add bulk processing when per-row DML dominates the run time on large sets, and always set
LIMIT. - Use
FOR UPDATEonly when you need to read, then change, the same rows safely. - Use
SYS_REFCURSORwhen the query is dynamic or the result set leaves your code.
Exercise
A procedure loops over 2 million rows with a cursor FOR loop. Inside the loop, it runs UPDATE orders SET status = 'ARCHIVED' WHERE orderid = r.orderid for each row where r.order_date < DATE '2020-01-01'. A colleague proposes switching to BULK COLLECT with LIMIT 1000 and FORALL. What would you recommend instead, and why?
Show answer
Replace the whole loop with one statement: UPDATE orders SET status = 'ARCHIVED' WHERE order_date < DATE '2020-01-01'. The loop applies no logic that SQL cannot express, so a single set-based UPDATE avoids all context switches and per-row overhead. BULK COLLECT with FORALL would be faster than the original loop, but it is still more code and slower than the single statement.
Exercise
A loop uses FETCH c BULK COLLECT INTO lrows LIMIT 100 followed by EXIT WHEN c%NOTFOUND, and then processes lrows. The table has 250 rows. How many rows are processed, and how do you fix it?
Show answer
Only 200 rows are processed. The third fetch returns 50 rows and sets %NOTFOUND to true, so the loop exits before processing them. Fix it by using EXIT WHEN l_rows.COUNT = 0 right after the fetch, or by moving the %NOTFOUND test after the processing code.
Exercise
You need a function that returns the employees of a department chosen by the caller, and the caller is a Java application. Which cursor type do you use, and who closes the cursor?
Show answer
Use a SYS_REFCURSOR, opened with OPEN ... FOR inside the function and returned to the caller. The calling application fetches from it and is responsible for closing it.