Sub topic 7
The cursor FOR loop
This chapter assumes you can write an anonymous PL/SQL block, declare variables, use basic LOOP control flow, and handle exceptions. You should also know how an explicit cursor is declared, opened, fetched and closed, and how %NOTFOUND and %ROWTYPE work. The cursor FOR loop wraps that whole lifecycle in one construct.
The problem it solves
A manual fetch loop needs four separate pieces of code: a %ROWTYPE record, OPEN, a FETCH with an EXIT WHEN ... %NOTFOUND test, and CLOSE. Each piece is a place to make a mistake. Forgetting CLOSE leaks a cursor. Putting the EXIT WHEN test before the FETCH gives an off-by-one result.
The cursor FOR loop removes all four pieces. Here is the manual version from the previous chapter:
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(r_emp.last_name || ': ' || r_emp.salary);
END LOOP;
CLOSE c_emp;
END;
/And here is the same logic as a cursor FOR loop:
DECLARE
CURSOR c_emp IS
SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 50
ORDER BY last_name;
BEGIN
FOR r_emp IN c_emp LOOP
DBMS_OUTPUT.PUT_LINE(r_emp.last_name || ': ' || r_emp.salary);
END LOOP;
END;
/The second block has no OPEN, FETCH, CLOSE or EXIT WHEN, and no record declaration. It produces the same output.
What the loop does for you
The loop performs these steps:
- It opens the cursor when the loop starts.
- It declares the loop record (
r_emp) implicitly, with the same structure as one row of the cursor's select list. - It fetches one row into the record at the top of each iteration.
- It exits when a fetch returns no row.
- It closes the cursor when the loop ends.
The cursor is also closed when the loop ends early, for example through EXIT, RETURN, GOTO out of the loop, or an unhandled exception that leaves the loop. You do not write cleanup code for these paths.
The loop record
The record named after FOR is declared by the loop itself. Its fields have the names of the select-list columns, or their aliases. Two rules follow from this:
- The record exists only between
LOOPandEND LOOP. You cannot readr_emp.last_nameafter the loop. - Do not declare a variable with the same name in the enclosing block. The loop record hides it inside the loop, which makes the code confusing.
Expressions in the select list need an alias, because the alias becomes the field name. Without one you cannot reference the value:
BEGIN
FOR r IN (SELECT last_name, salary * 12 AS annual_salary
FROM employees
WHERE department_id = 50)
LOOP
DBMS_OUTPUT.PUT_LINE(r.last_name || ': ' || r.annual_salary);
END LOOP;
END;
/The record is read-only in one important sense: you can read its fields but you cannot assign to them. r.salary := 0; fails to compile. Copy the value into a variable if you need to change it.
Inline queries
When the query is used in only one place, you can put it directly in the loop header. No CURSOR declaration is needed, and the block has no DECLARE section:
BEGIN
FOR r IN (SELECT department_id, COUNT(*) AS cnt
FROM employees
GROUP BY department_id
ORDER BY department_id)
LOOP
DBMS_OUTPUT.PUT_LINE(r.department_id || ': ' || r.cnt);
END LOOP;
END;
/The alias cnt becomes the field r.cnt. The query must be a SELECT written in the header, and the parentheses are required.
Use a named cursor when the same query is needed in more than one place, when it takes parameters, or when you want to refer to the cursor's attributes. An inline query has no name, so you cannot write c_emp%ROWCOUNT for it.
| Form | Cursor declared separately | Reusable | Can use cursor name for attributes |
|---|---|---|---|
| `FOR r IN c_emp LOOP` | Yes | Yes | Yes |
| `FOR r IN (SELECT ...) LOOP` | No | No | No |
Passing parameters
A named cursor with parameters is opened by the loop, so the arguments go in the loop header:
DECLARE
CURSOR c_emp (p_dept NUMBER, p_min_sal NUMBER DEFAULT 0) IS
SELECT last_name, salary
FROM employees
WHERE department_id = p_dept
AND salary >= p_min_sal;
BEGIN
FOR r IN c_emp(50, 3000) LOOP
DBMS_OUTPUT.PUT_LINE(r.last_name || ': ' || r.salary);
END LOOP;
END;
/p_min_sal has a default, so FOR r IN c_emp(50) LOOP also works and uses 0. You can call the same cursor twice in one block with different arguments, because each loop opens and closes its own instance.
Counting rows and detecting an empty result
Because you do not write the fetch, the usual %NOTFOUND test is not available for control flow. The loop body never runs when the query returns no rows, and nothing is raised. If you need to know whether any row was processed, keep your own counter:
DECLARE
l_count PLS_INTEGER := 0;
BEGIN
FOR r IN (SELECT last_name FROM employees WHERE department_id = 999) LOOP
l_count := l_count + 1;
DBMS_OUTPUT.PUT_LINE(r.last_name);
END LOOP;
IF l_count = 0 THEN
DBMS_OUTPUT.PUT_LINE('No employees found.');
END IF;
END;
/With a named cursor, c_emp%ROWCOUNT is valid inside the loop body and returns the number of rows fetched so far. Outside the loop the cursor is closed, so its attributes cannot be used there. Referring to c_emp%ROWCOUNT after END LOOP raises INVALID_CURSOR, ORA-01001. c_emp%ISOPEN is true inside the loop and false after it.
Changing data inside the loop
The loop body can run DML, including DML against the same table the cursor reads. The cursor sees a consistent snapshot as of the time it was opened, so rows you change inside the loop do not alter which rows the cursor returns.
When you need to update the row just fetched, use FOR UPDATE and WHERE CURRENT OF. The FOR UPDATE clause locks the rows when the cursor opens, and NOWAIT raises an error instead of waiting if another session holds a lock:
DECLARE
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;
END;
/Commit after the loop, not inside it. A COMMIT releases the locks that FOR UPDATE took. A later fetch from the same cursor then fails with ORA-01002, "fetch out of sequence".
Gotchas
- Row-by-row cost. Each iteration that runs a SQL statement in the body causes a switch between the PL/SQL and SQL engines. A loop that issues one
UPDATEper row is slow on large data sets. Prefer a singleUPDATEstatement when the logic fits in SQL. - Implicit bulk fetching. Oracle's optimizing compiler, at the default
PLSQL_OPTIMIZE_LEVELof 2, typically rewrites a cursor FOR loop so that it fetches 100 rows per round trip. This helps read speed but does not reduce the context switches caused by DML inside the body. - Exceptions in the body. An unhandled exception leaves the loop and the cursor is closed. If you catch the exception inside the loop with a nested block, the loop continues with the next row.
- Cursor variables. The cursor FOR loop works with static cursors and inline queries. It does not accept a
SYS_REFCURSORvariable. UseOPEN,FETCHandCLOSEfor those. - Leaving early.
EXIT WHENworks as in any loop. Use it for a stop condition that depends on row data, and the cursor is still closed for you.
Choosing the loop form
Use a cursor FOR loop when you need to process each row in PL/SQL and the work does not fit in one SQL statement. Pick the inline form for a one-off query, and the named form for a reused query, parameters, or FOR UPDATE. Move to manual OPEN and FETCH when you need SYS_REFCURSOR, or to BULK COLLECT ... LIMIT when you need explicit control over batch size, as later chapters show.
Exercise
A block uses FOR r IN c_emp LOOP ... END LOOP; and, on the line after END LOOP;, prints c_emp%ROWCOUNT. What happens, and how would you get the total number of rows processed?
Show answer
The cursor is closed when the loop ends, so referring to c_emp%ROWCOUNT after END LOOP raises ORA-01001 (INVALIDCURSOR). To keep the total, declare a variable such as `lcount PLSINTEGER := 0;, add 1 to it in each iteration, and read it after the loop. You can also copy cemp%ROWCOUNT` into a variable inside the loop body.
Exercise
You loop over a FOR UPDATE cursor, update each row with WHERE CURRENT OF, and put COMMIT; as the last statement inside the loop body. The first iteration works and the second fails. Which error do you get, and how do you fix the code?
Show answer
The second fetch fails with ORA-01002 (fetch out of sequence), because the commit released the locks held by the FOR UPDATE cursor. Move the COMMIT; to after END LOOP; so that it runs once, when all rows have been processed.