Sub topic 13
Looping Over Query Results with a Cursor FOR LOOP
This chapter assumes you can write an anonymous PL/SQL block, write a basic SELECT ... WHERE query, and have read the earlier chapters on the numeric FOR loop, EXIT, and CONTINUE. Examples use the Oracle HR sample schema and need SET SERVEROUTPUT ON in SQL*Plus or SQLcl.
A cursor FOR loop runs its body once for each row a query returns. It opens the query, fetches each row, and closes the cursor for you. You write only the query and the work to do per row.
The Basic Form
BEGIN
FOR r IN (SELECT employee_id, last_name
FROM employees
WHERE department_id = 50
ORDER BY employee_id) LOOP
DBMS_OUTPUT.PUT_LINE(r.employee_id || ' ' || r.last_name);
END LOOP;
END;
/The loop has three parts.
ris a record variable. You do not declare it. PL/SQL creates it with one field for each column in the select list.- You read a field with dot notation, such as
r.last_name. rexists only betweenLOOPandEND LOOP. Referring to it afterwards causes a compile error.
The loop works like a numeric FOR loop, except the "counter" is a whole row.
What PL/SQL Does for You
The same work written by hand with an explicit cursor takes more code:
DECLARE
CURSOR c_emp IS
SELECT employee_id, last_name
FROM employees
WHERE department_id = 50
ORDER BY employee_id;
r c_emp%ROWTYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO r;
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(r.employee_id || ' ' || r.last_name);
END LOOP;
CLOSE c_emp;
END;
/The cursor FOR loop removes four things you could get wrong: the OPEN, the FETCH, the EXIT WHEN ... %NOTFOUND test, and the CLOSE. A forgotten CLOSE leaks an open cursor, and Oracle limits how many a session can hold (the OPEN_CURSORS parameter). The FOR loop cannot leak one.
The diagram shows the sequence the loop runs.
Choosing Between Inline and Named Cursors
You can write the query inline, as in the first example, or declare a named cursor and refer to it in the loop. A named cursor can take parameters and can be reused.
DECLARE
CURSOR c_dept_emp (p_dept NUMBER, p_min_salary NUMBER) IS
SELECT employee_id, last_name, salary * 12 AS annual_pay
FROM employees
WHERE department_id = p_dept
AND salary >= p_min_salary
ORDER BY employee_id;
l_count PLS_INTEGER := 0;
BEGIN
FOR r IN c_dept_emp(50, 3000) LOOP
l_count := l_count + 1;
DBMS_OUTPUT.PUT_LINE(r.last_name || ': ' || r.annual_pay);
END LOOP;
DBMS_OUTPUT.PUT_LINE('Rows processed: ' || l_count);
END;
/Two details matter here.
- Expressions need an alias. The column
salary * 12has no usable field name, soAS annual_payprovides one. Without the alias, you cannot refer to the value asr.annual_pay. - Count rows yourself. After the loop, the cursor is closed and
ris out of scope. Use a counter variable if you need the row total.
| Aspect | Inline query | Named cursor |
|---|---|---|
| Declaration | None | `CURSOR` in the declaration section |
| Parameters | Use PL/SQL variables from the enclosing block | Formal parameters, passed at the `FOR` |
| Reuse | One loop only | Any number of loops |
| Best for | A short query used once | A query used in several places, or one that needs parameters |
Zero Rows Is Not an Error
If the query returns no rows, the loop body runs zero times and execution continues after END LOOP. No exception is raised. Compare this with SELECT ... INTO, which raises NO_DATA_FOUND for zero rows and TOO_MANY_ROWS for more than one.
To detect an empty result, set a flag inside the loop:
DECLARE
l_found BOOLEAN := FALSE;
BEGIN
FOR r IN (SELECT last_name
FROM employees
WHERE department_id = 999) LOOP
l_found := TRUE;
DBMS_OUTPUT.PUT_LINE(r.last_name);
END LOOP;
IF NOT l_found THEN
DBMS_OUTPUT.PUT_LINE('No employees in that department');
END IF;
END;
/This ties back to the first chapter of this tutorial. l_found is never NULL here, so NOT l_found is reliably TRUE or FALSE.
Controlling the Loop
EXIT, EXIT WHEN, CONTINUE, CONTINUE WHEN, and labels all work inside a cursor FOR loop. Leaving early still closes the cursor.
DECLARE
l_total NUMBER := 0;
BEGIN
<<emp_loop>>
FOR r IN (SELECT last_name, salary
FROM employees
WHERE department_id = 50
ORDER BY salary DESC) LOOP
CONTINUE emp_loop WHEN r.salary < 3000;
l_total := l_total + r.salary;
EXIT emp_loop WHEN l_total > 10000;
DBMS_OUTPUT.PUT_LINE(r.last_name || ' running total: ' || l_total);
END LOOP emp_loop;
DBMS_OUTPUT.PUT_LINE('Final total: ' || l_total);
END;
/The loop skips low-paid employees, then stops as soon as the running total passes 10,000. The label is optional here. It becomes useful when a cursor loop sits inside another loop and you need to leave or continue the outer one.
An exception raised inside the body also closes the cursor as it leaves the loop. If the surrounding block has an EXCEPTION section, you do not need cleanup code for the cursor.
Gotchas
Name Capture
Inside a SQL statement embedded in PL/SQL, a name that matches both a column and a local variable resolves to the column. This query does not do what it appears to do:
DECLARE
department_id NUMBER := 50;
BEGIN
FOR r IN (SELECT last_name
FROM employees
WHERE department_id = department_id) LOOP
DBMS_OUTPUT.PUT_LINE(r.last_name);
END LOOP;
END;
/Both sides of the comparison are the column employees.department_id. The condition is true for every row with a non-null department, so the loop prints nearly all employees. Prefix variables (l_dept_id) or qualify them with the block label to avoid this.
Modifying the Loop Record
The record r is read-only in a cursor FOR loop. A statement such as r.salary := r.salary * 1.1; fails to compile. Copy the value to a local variable if you need to change it.
Updating the Row You Are On
To update the current row, declare the cursor with FOR UPDATE and use WHERE CURRENT OF:
DECLARE
CURSOR c_emp IS
SELECT employee_id, salary
FROM employees
WHERE department_id = 50
FOR UPDATE;
BEGIN
FOR r IN c_emp LOOP
UPDATE employees
SET salary = r.salary * 1.05
WHERE CURRENT OF c_emp;
END LOOP;
ROLLBACK;
END;
/FOR UPDATE locks the selected rows until the transaction ends. The ROLLBACK at the end keeps this demonstration from changing the sample data. In real code, hold the locks for as short a time as you can. When you do not need row-by-row logic, a single UPDATE statement is simpler (see the last section).
Performance Notes
A cursor FOR loop fetches rows from the SQL engine into the PL/SQL engine. With the default PLSQL_OPTIMIZE_LEVEL of 2 or higher, the compiler fetches in batches of 100 rows behind the scenes. This gives you most of the benefit of BULK COLLECT without extra code. At optimization level 1 or 0, it fetches one row at a time.
The loop is not free. Every SQL statement you run inside the body, such as an INSERT or UPDATE per row, causes a switch between the PL/SQL and SQL engines. For thousands of rows, those switches add up. If the body only runs one DML statement using the row's values, the loop can often be a single set-based SQL statement. The final chapter in this section covers that decision.
Common Errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `PLS-00201` or `PLS-00302` on `r.something` | Column missing from the select list, or an expression without an alias | Add the column or an `AS` alias |
| `r` not recognized after `END LOOP` | The record's scope ends with the loop | Copy values to variables inside the loop |
| Loop returns far more rows than expected | Variable has the same name as a column | Rename the variable, such as `l_dept_id` |
| `INVALID_CURSOR` when reading `%ROWCOUNT` after the loop | The cursor is already closed | Count rows with your own variable |
| `ORA-01002` after a `COMMIT` in the loop | Fetching across commit with `FOR UPDATE` | Move the commit outside the loop |
Exercise
What does this block print, and why? DECLARE ln PLSINTEGER := 0; BEGIN FOR r IN (SELECT 1 AS x FROM dual WHERE 1 = 0) LOOP ln := ln + 1; END LOOP; DBMSOUTPUT.PUTLINE('Count: ' || l_n); END;
Show answer
It prints "Count: 0". The query returns no rows, so the loop body never runs, and no exception such as NODATAFOUND is raised. Execution continues after END LOOP.
Exercise
A colleague writes FOR r IN (SELECT lastname, salary * 12 FROM employees) LOOP and then refers to r.salary12 in the body. Why does this fail, and how do you fix it?
Show answer
The expression salary 12 has no column alias, so the record has no field named salary_12. Add an alias in the select list, such as salary 12 AS annualpay, and refer to r.annualpay.
Exercise
Rewrite the explicit-cursor example (OPEN, FETCH, EXIT WHEN %NOTFOUND, CLOSE) as a cursor FOR loop. Which statements disappear, and what happens to the record variable?
Show answer
FOR r IN (SELECT employeeid, lastname FROM employees WHERE departmentid = 50 ORDER BY employeeid) LOOP ... END LOOP; The OPEN, FETCH, EXIT WHEN %NOTFOUND, and CLOSE statements disappear. The record r no longer needs a declaration with %ROWTYPE, because the loop declares it implicitly and limits its scope to the loop body.