Sub topic 1
What a cursor is
SQL works on sets of rows. A SELECT can return zero rows, one row, or a million rows, and the statement treats them as one result. PL/SQL is a procedural language and handles one value or one record at a time. A cursor connects the two. This chapter explains what a cursor is, where it lives, how it moves through its life, and why the later chapters (explicit cursors, cursor FOR loops, BULK COLLECT) are all variations on one idea.
Prerequisites
This chapter assumes you already know:
- Basic SQL:
SELECT,INSERT,UPDATE,DELETEandWHERE. - The structure of an anonymous PL/SQL block (
DECLARE,BEGIN,EXCEPTION,END). - PL/SQL variables, data types and basic control flow (
IF,LOOP). - Basic exception handling, such as
WHEN OTHERSand named exceptions.
The examples use the employees table from the Oracle sample HR schema. Run SET SERVEROUTPUT ON in SQL*Plus or SQLcl first so that DBMS_OUTPUT text appears.
The problem a cursor solves
Consider this statement:
SELECT last_name, salary
FROM employees
WHERE department_id = 50;Department 50 may have dozens of employees. A PL/SQL variable such as l_name VARCHAR2(25) holds one name. If you write SELECT ... INTO l_name, the query must return exactly one row. Oracle needs somewhere to keep the state of a multi-row query between your requests for each row: which statement is running, what its bind values are, and which row comes next. A cursor is that place.
Cursor and context area
A cursor is a handle to a private memory structure that Oracle builds to process one SQL statement. The Oracle documentation calls this structure the context area. It is also called the private SQL area. For a dedicated server connection it lives in the session's Program Global Area (PGA).
The context area holds the runtime state of the statement:
- The values of the bind variables for this execution.
- A pointer to the parsed statement and execution plan, which are shared across sessions in the shared SQL area of the library cache.
- The position within the result set: the row you fetched last and the row you get next.
- Counters such as the number of rows processed so far.
Oracle does not copy a query's full result into the context area when the query starts. It produces rows as you fetch them. The set of rows that the query returns is called the active set.
The result is also fixed at the moment the cursor is opened. Oracle gives the cursor a read-consistent view of the data as of that moment. If another session commits a change while you are still fetching, you do not see that change through the open cursor.
How Oracle processes a statement
Every SQL statement that runs from PL/SQL goes through the same stages. A cursor exists across these stages.
- Parse. Oracle checks the syntax and the privileges, and finds or builds an execution plan. If an identical statement is already in the shared SQL area, Oracle reuses its plan. This is why using bind variables instead of concatenated literals matters for performance.
- Bind. Oracle attaches the current values of any PL/SQL variables used in the statement.
- Execute. For a
SELECT, Oracle prepares to return rows and positions the cursor before the first one. For DML, Oracle does the work here and changes the rows. - Fetch. Only queries use this stage. Each fetch returns one row, or a batch of rows, and moves the position forward.
- Close. Oracle releases the context area so its memory can be reused.
In PL/SQL, an implicit cursor performs all five stages for you. With an explicit cursor you control the stages yourself, through OPEN, FETCH and CLOSE. The later chapters cover those statements in detail.
Implicit and explicit cursors
PL/SQL has two main kinds of cursor, and a third kind that shares features with both.
| Kind | Who manages it | Typical statements | Rows returned |
|---|---|---|---|
| Implicit cursor | Oracle, automatically | `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `SELECT ... INTO` | Zero or one row for `SELECT INTO`; any number of rows affected for DML |
| Explicit cursor | You, with `CURSOR`, `OPEN`, `FETCH`, `CLOSE` | Multi-row `SELECT` | Any number of rows, one at a time |
| Cursor variable (`REF CURSOR`) | You, like an explicit cursor | A query chosen at run time | Any number of rows |
Oracle opens an implicit cursor for every SQL statement you run in PL/SQL that you did not attach to an explicit cursor. You never see it by name, but you can inspect its result through the SQL cursor attributes, such as SQL%ROWCOUNT. You can also run SELECT INTO as many times as you like without writing any cursor code.
An explicit cursor is a named query. You declare it in the declaration section, and it stays unused until you open it. Use one whenever the query can return more than one row and you need to process each row separately.
A worked example: one implicit cursor
This block uses an implicit cursor, because SELECT ... INTO is a single-row query. It also shows what happens when the one-row assumption is wrong.
SET SERVEROUTPUT ON
DECLARE
l_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE department_id = 50;
DBMS_OUTPUT.PUT_LINE('Found: ' || l_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee in that department');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('More than one employee in that department');
END;
/In the standard HR data, department 50 has several employees, so this block prints More than one employee in that department. Oracle's implicit cursor fetched the first row, tried to fetch a second, and raised TOO_MANY_ROWS. If you change the department to one with no employees, the block raises NO_DATA_FOUND instead. If you change the WHERE clause to employee_id = 100, it prints one name.
This shows the limit of the implicit SELECT INTO: it demands exactly one row. When a query can return several rows, you need a cursor that lets you step through them. That is an explicit cursor, or a cursor FOR loop, which is the shortest way to write one.
Where a cursor fits in a program
A PL/SQL block runs in the PL/SQL engine, and the SQL it contains runs in the SQL engine. Each time the block needs a SQL statement executed, control passes from one engine to the other. This is a context switch. A cursor is the object the two engines share while a statement is open.
Context switches have a cost. A loop that fetches 10,000 rows one at a time makes 10,000 switches. Later chapters show how BULK COLLECT with LIMIT reduces that cost by fetching rows in batches. The first rule, though, is to ask whether you need a cursor loop at all. A single UPDATE that changes every row you want is nearly always faster than a loop that fetches each row and updates it. A cursor loop is justified when each row needs its own procedural logic.
Limits and resource use
Each open cursor holds memory and counts against a limit.
- The initialization parameter
OPEN_CURSORSsets the maximum number of cursors a session can have open at once. Exceeding it raisesORA-01000: maximum open cursors exceeded. - A cursor that you open and never close keeps its context area for as long as the session lives, or until the block that declared it ends. Code that opens a cursor in a loop without closing it can reach
ORA-01000in production long after it passed testing. - Implicit cursors are closed by Oracle. Cursor FOR loops also close their cursors for you, even when the loop exits through an exception. Manually opened explicit cursors are your responsibility.
You can see a session's open cursors with the view V$OPEN_CURSOR, which requires the right privileges. A DBA can use the same view to find sessions that leak cursors.
Where this chapter leads
The rest of the tutorial follows from the model in this chapter:
- Implicit cursors expose their results through
SQL%ROWCOUNTand related attributes. - Explicit cursors let you control parse, execute, fetch and close yourself.
- Cursor attributes such as
%FOUNDand%NOTFOUNDtell you where the cursor is in its fetch sequence. - The cursor FOR loop performs open, fetch and close for you.
- Parameters,
FOR UPDATE,REF CURSORandBULK COLLECTchange how the cursor is defined, locked, passed or fetched.
Each of these topics changes one stage of the lifecycle in the diagram above. If you keep that lifecycle in mind, none of them is new machinery.
Exercises
Exercise
Where does Oracle keep the context area for a cursor, and which three kinds of information does it hold about the statement?
Show answer
For a dedicated server connection the context area (the private SQL area) is in the session's PGA. It holds the bind variable values for this execution, a pointer to the parsed statement and plan in the shared SQL area, and the current position in the result set together with counters such as rows processed.
Exercise
A block runs SELECT salary INTO l_salary FROM employees WHERE department_id = 50; and fails with ORA-01422, which PL/SQL reports as TOO_MANY_ROWS. Why does the implicit cursor fail, and what kind of cursor would let you process every row?
Show answer
An implicit SELECT ... INTO expects exactly one row. Department 50 has several employees, so Oracle fetches a second row and raises the error. An explicit cursor (or a cursor FOR loop, which manages one for you) lets you fetch the rows one at a time.
Exercise
A session raises ORA-01000: maximum open cursors exceeded after running a procedure many times. The procedure opens an explicit cursor inside a loop. What is the likely cause, and what should you check before raising OPEN_CURSORS?
Show answer
The procedure probably opens the cursor and does not close it on every path, for example when an exception skips the CLOSE statement. Check that every OPEN has a matching CLOSE, including in the exception handler, or switch to a cursor FOR loop, which closes automatically. Raising OPEN_CURSORS only hides the leak.