Sub topic 8
Cursor FOR Loop with an Inline Query
This chapter assumes you can write an anonymous PL/SQL block and a basic SELECT. It also assumes you have seen the named cursor FOR loop from the previous chapter. Here you drop the CURSOR declaration and put the query directly in the loop header.
What an inline cursor FOR loop is
An inline cursor FOR loop takes the SELECT statement in parentheses right after IN. Oracle still creates a cursor, but it has no name and no declaration section entry.
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;
/For this loop Oracle does the following:
- Opens the cursor for the query.
- Declares the loop record
rimplicitly. - Fetches one row into
ron each iteration. - Exits when no rows remain and closes the cursor.
You write no OPEN, FETCH, CLOSE or %NOTFOUND test. Those steps are the main source of cursor leaks and endless loops in hand-written fetch loops, and the inline form removes them.
The loop record
The record r is created for you. Its fields match the select list, so each column or alias in the query becomes a field. Three rules follow from this.
- Expressions need aliases. In the example above,
COUNT(*)is reachable asr.cntonly because ofAS cnt. Without the alias the loop still runs, but you have no name to read the value by. - Names must be unique. If two select-list items resolve to the same name, as with a join that returns
department_idfrom two tables, Oracle raisesPLS-00402. Alias one of them. - The record is read-only and scoped to the loop. Assigning to
r.cntinside the loop fails to compile withPLS-00363. AfterEND LOOPthe namerno longer exists. If you need a value afterwards, copy it into a variable declared outside the loop.
Using PL/SQL variables in the query
The inline query can reference PL/SQL variables and parameters. Oracle treats them as bind variables, which means the values are passed to the SQL engine rather than concatenated into the text. This avoids SQL injection and lets Oracle reuse the parsed statement.
DECLARE
l_dept employees.department_id%TYPE := 50;
l_rows PLS_INTEGER := 0;
l_total NUMBER := 0;
BEGIN
FOR r IN (SELECT last_name,
salary,
salary * 12 AS annual
FROM employees
WHERE department_id = l_dept
ORDER BY last_name)
LOOP
l_rows := l_rows + 1;
l_total := l_total + r.annual;
DBMS_OUTPUT.PUT_LINE(r.last_name || ': ' || r.annual);
END LOOP;
DBMS_OUTPUT.PUT_LINE(l_rows || ' rows, total ' || l_total);
END;
/Oracle reads l_dept once, when the cursor opens. If the loop body changes l_dept, the running query is not affected. The example also counts rows with its own variable, because the cursor has no name and you cannot write c_emp%ROWCOUNT.
Cursor attributes are not available
With a named cursor you can test c_emp%ISOPEN or read c_emp%ROWCOUNT. An inline cursor has no name, so there is nothing to put before the %. The common workarounds are:
- Keep a counter variable, as in the example above.
- Set a flag inside the loop if you need to know whether any row was processed. The flag stays false when the query returns no rows, because the body never runs.
- Switch to a named cursor if you need attributes frequently.
SQL%ROWCOUNT does not report on the loop query either. It describes the most recent implicit cursor, such as a DML statement run inside the loop body.
DML inside the loop
The loop body often changes data, using the fetched values to find rows.
DECLARE
l_updated PLS_INTEGER := 0;
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;
l_updated := l_updated + SQL%ROWCOUNT;
END LOOP;
DBMS_OUTPUT.PUT_LINE(l_updated || ' rows updated');
COMMIT;
END;
/Here SQL%ROWCOUNT is valid because it follows the UPDATE, which is an implicit cursor. This pattern is correct but slow for large tables, because each iteration switches between the PL/SQL and SQL engines. When one UPDATE employees SET salary = salary * 1.05 WHERE department_id = 50 does the same job, prefer it. Use the loop only when each row needs logic that SQL cannot express.
If you need to lock the rows you read, the inline form is not enough. FOR UPDATE with WHERE CURRENT OF needs a named cursor, so use the declared form shown in the locking chapter.
Nested loops
Each inline query is its own cursor, so loops can be nested. The inner query can reference the outer record, which makes a master-detail report easy to write.
BEGIN
FOR d IN (SELECT department_id, department_name
FROM departments
ORDER BY department_id)
LOOP
DBMS_OUTPUT.PUT_LINE('Department ' || d.department_name);
FOR e IN (SELECT last_name
FROM employees
WHERE department_id = d.department_id
ORDER BY last_name)
LOOP
DBMS_OUTPUT.PUT_LINE(' ' || e.last_name);
END LOOP;
END LOOP;
END;
/The inner query opens once per outer row. For a few departments that is fine. For thousands of outer rows, a single join with a ORDER BY and control-break logic in one loop is usually faster.
Use different record names for the two loops. If both were called r, the inner r would hide the outer one and the reference to d.department_id would be a bug waiting to happen.
Leaving the loop early
EXIT and EXIT WHEN work as in any loop. Oracle closes the cursor on the way out, and it does the same if an exception propagates out of the body.
DECLARE
l_seen PLS_INTEGER := 0;
BEGIN
FOR r IN (SELECT last_name, salary
FROM employees
ORDER BY salary DESC)
LOOP
l_seen := l_seen + 1;
EXIT WHEN l_seen > 3;
DBMS_OUTPUT.PUT_LINE(r.last_name || ': ' || r.salary);
END LOOP;
END;
/For a top-N result like this, a FETCH FIRST 3 ROWS ONLY clause in the query is better, because the database stops sooner and sends fewer rows. Early EXIT is for conditions that depend on values PL/SQL computes.
Performance behavior
With the default PLSQL_OPTIMIZE_LEVEL of 2 or higher, the PL/SQL compiler rewrites a cursor FOR loop to fetch rows in batches of 100, as if you had written BULK COLLECT ... LIMIT 100. You write row-by-row code and get most of the batch-fetch benefit for the read side. This does not apply to the DML you run inside the body, which still executes once per row. If you lower the optimization level to 1 or 0, the rewrite does not happen.
When not to use the inline form
| Situation | Better choice |
|---|---|
| The same query is needed in several places | Named cursor, so the SQL text lives once |
| You need `%ROWCOUNT`, `%ISOPEN` or `%FOUND` | Named cursor with explicit fetch |
| You need `WHERE CURRENT OF` | Named cursor with `FOR UPDATE` |
| Arguments should be checked by the compiler | Parameterized named cursor |
| The query text is built at run time | `OPEN ... FOR` with a `SYS_REFCURSOR` |
| Each row needs only a simple data change | One SQL statement |
Common mistakes
- Missing alias on an expression. The loop compiles, but
r.somethinghas no valid name. Alias every expression. - Reading the record after the loop. The record is out of scope at
END LOOP. Copy what you need into variables. - Trying
cursor%NOTFOUNDon the inline query. There is no cursor name. Use a counter. - Assigning to a loop record field. The record is read-only. Copy to a local variable first.
- Reusing the record name in nested loops. The inner name hides the outer one.
- Adding
OPENorCLOSEto a FOR loop. These statements do not apply here, since Oracle handles both.
Exercise
The following block fails to compile. Name the cause and fix it. BEGIN FOR r IN (SELECT departmentid, MAX(salary) FROM employees GROUP BY departmentid) LOOP DBMSOUTPUT.PUTLINE(r.departmentid || ': ' || r.maxsal); END LOOP; END; /
Show answer
The expression MAX(salary) has no alias, so the record has no field called maxsal. Write MAX(salary) AS maxsal in the select list. The loop then runs and prints one line per department.
Exercise
Write an inline cursor FOR loop that prints the last name of every employee in department 50, and afterwards prints how many rows it processed. Why can't you use a cursor attribute for the count?
Show answer
DECLARE lcount PLSINTEGER := 0; BEGIN FOR r IN (SELECT lastname FROM employees WHERE departmentid = 50 ORDER BY lastname) LOOP lcount := lcount + 1; DBMSOUTPUT.PUTLINE(r.lastname); END LOOP; DBMSOUTPUT.PUTLINE(l_count || ' rows'); END; / An inline cursor has no name, so there is nothing to put before %ROWCOUNT. A counter variable gives the same information, and the record r is out of scope after END LOOP.