Sub topic 7
The Cursor FOR Loop
What the cursor FOR loop does
Prerequisites: you should know basic SELECT statements and the structure of an anonymous PL/SQL block. You should also understand variables, loops, and records.
A cursor FOR loop processes the rows returned by a query one at a time. The loop automatically:
- Opens the cursor.
- Fetches each row into a record.
- Stops after the last row.
- Closes the cursor.
The loop variable is an implicitly declared record. Its fields match the columns in the cursor's select list. You do not declare the record, write OPEN, call FETCH, or write CLOSE.
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;
/Here, c_emp is a named explicit cursor. The FOR r_emp IN c_emp statement creates r_emp for the loop. Within the loop, r_emp.employee_id, r_emp.last_name, and r_emp.salary refer to the selected columns.
The record exists only inside the loop. You cannot refer to r_emp after END LOOP.
The loop lifecycle
The following diagram shows the work performed by Oracle:
The body runs once for every row. If the query returns no rows, the body runs zero times. This is different from a loop that assumes at least one row and tries to process an uninitialized record.
Use an inline query
You can place the query directly in the FOR statement when you do not need to reuse or name the cursor:
BEGIN
FOR r IN (
SELECT department_id, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id
ORDER BY department_id
)
LOOP
DBMS_OUTPUT.PUT_LINE(
r.department_id || ': ' || r.employee_count
);
END LOOP;
END;
/The alias employee_count becomes a field of the loop record. Always give expressions and calculated values clear aliases so the field names are predictable.
A named cursor is useful when the query has a meaningful name or will be used by more than one loop. An inline query is convenient for a single use. In both forms, Oracle controls opening, fetching, and closing.
Common mistakes
- Do not write
OPEN,FETCH, orCLOSEfor a cursor FOR loop. Those operations are automatic. - Do not declare the loop record separately.
- Refer to fields by their select-list names or aliases.
- Do not expect the loop body to run when the query returns no rows.
- Keep the loop body focused. If one SQL statement can perform the entire operation, it is often clearer and faster than processing rows individually.
Exercise
In the inline-query example, what is the name of the record field containing the employee count?
Show answer
The field is employee_count, because the select list gives COUNT(*) the alias employee_count.