Sub topic 13
Looping Over Query Results with a Cursor FOR LOOP
Assume you know how to write SELECT statements and anonymous PL/SQL blocks. This chapter focuses on processing each row returned by a query.
A cursor is a handle for a result set, which is the rows produced by a query. A cursor FOR loop automatically opens the cursor, fetches one row at a time, and closes the cursor when the loop finishes. You do not need separate OPEN, FETCH, or CLOSE statements.
Basic Cursor FOR LOOP
The loop variable is an implicitly declared record. A record is a variable containing fields, such as the columns returned by the query. Use the column names or aliases with dot notation.
DECLARE
l_limit PLS_INTEGER := 4;
BEGIN
FOR r IN (
SELECT level AS task_id,
'Task ' || level AS task_name
FROM dual
CONNECT BY level <= l_limit
) LOOP
DBMS_OUTPUT.PUT_LINE(
r.task_id || ': ' || r.task_name
);
END LOOP;
END;
/The query returns four rows. On each iteration, r contains the current row. The loop variable r exists only inside the loop, so you cannot reference it after END LOOP.
You can use any valid query, including joins, filters, expressions, and ordering:
BEGIN
FOR employee_row IN (
SELECT employee_id, last_name
FROM employees
WHERE department_id = 50
ORDER BY last_name
) LOOP
DBMS_OUTPUT.PUT_LINE(
employee_row.employee_id || ' ' ||
employee_row.last_name
);
END LOOP;
END;
/This example assumes the Oracle HR sample schema and that the session can read employees.
What Happens During the Loop
The execution sequence is:
The query is evaluated when the loop starts. If it returns no rows, the loop body runs zero times. This is normal behavior and does not raise NO_DATA_FOUND.
Common Errors and Good Practices
| Situation | Result or practice |
|---|---|
| Query returns no rows | The loop body is skipped |
| Column has no convenient name | Give it an alias |
| Need a row value | Use `row_variable.column_name` |
| Need the loop record after the loop | Copy needed values to another variable |
| Need a predictable order | Add `ORDER BY` to the query |
Use aliases when expressions would otherwise create unclear column names. Keep the loop body focused on row-by-row work, such as formatting output or calling a procedure. If the work can be expressed as one SQL statement, that is often clearer and faster than processing rows individually.
The cursor FOR loop is usually the best choice when you need every result row but do not need manual control over cursor operations. It reduces resource-management errors because Oracle handles opening, fetching, and closing the cursor.
Exercise
What happens if a cursor FOR LOOP query returns zero rows, and where can you reference the implicitly declared loop record?
Show answer
The loop body runs zero times. The loop record can be referenced only inside that loop.