Oracle Connections, Cursors, and the SQL Cache
In Oracle, a cursor is the whole memory structure used to run one SQL statement. Not only SELECT but also INSERT, UPDATE, and PL/SQL blocks run as cursors. A cursor has two parts. The part that is the same for everyone, such as the statement text and the execution plan, is kept once in the SGA shared pool (the shared cursor). The part that differs per session, such as bind values and the execution position, is kept in that session's PGA. Because of this structure, Oracle performance discussions always center on "how often do we parse anew?"
Key Specifications
| Item | Value |
|---|---|
| Protocol | Oracle Net (TNS). Default listener port 1521 |
| Connection and session | A connection is a network path and a session is a logged-in state. One connection can have no session or several |
| Server placement | Dedicated server (default), shared server (dispatcher), DRCP (pooled server) |
| Limits | PROCESSES, SESSIONS (default 1.5 × PROCESSES + 22) |
| Where shared cursors live | The library cache in the shared pool |
| Cursor identification | SQL_ID: a hash of the statement text. Different whitespace or letter case makes a different statement |
| Open cursor limit per session | OPEN_CURSORS, default 50 (300 in the sandbox). Exceeding it raises ORA-01000 |
| Session cursor cache | SESSION_CACHED_CURSORS, default 50. The session keeps the closed cursors of statements parsed more than three times |
| Literal handling | CURSOR_SHARING, default EXACT. With FORCE, literals are replaced with system bind variables |
| Result cache | Server result cache. RESULT_CACHE_MODE defaults to MANUAL (only queries with the hint) |
| Server cursor direction | Forward only. Scrolling is emulated by the client driver collecting the results |
| Commit and cursors | Open cursors are not closed by a commit (except FOR UPDATE cursors) |
Connections
Figure. Three server placements
flowchart TB
CL["Client"] -->|"Connection request by service name"| LS["Listener"]
LS -->|"Dedicated server"| DS["Server process<br/>one per session, until the session ends"]
LS -->|"Shared server"| DP["Dispatcher Dnnn"]
DP --> RQ["Request queue (SGA)"]
RQ --> SS["Shared server Snnn<br/>handles one request, then the next"]
SS --> RP["Response queue (SGA)"]
RP --> DP
LS -->|"DRCP"| CB["Connection broker"]
CB --> PS["Pooled server<br/>assigned only while the session is in use"]
DS --> DB["SGA, database"]
SS --> DB
PS --> DB
Diagram description: The Listener splits into three branches.
- Dedicated server. The listener creates a server process and hands the connection to it, and that process serves only that session until the session ends. The session state (UGA) lives in that process's PGA. This is the default.
- Shared server. The client stays attached to a
Dispatcher, which puts requests into theRequest queuein the SGA. An idleShared serverprocess takes a request from the queue and runs it, and when it puts the result into theResponse queue, the dispatcher returns it to the client. Because a different process can handle each request, the session state lives in the SGA (large pool). - DRCP (Database Resident Connection Pooling). The
Connection brokerholds the client connection and assigns aPooled serveronly while the application is actually using the session. Like a dedicated server, a pooled server holds the session state in its own PGA, and when it is released it goes to another client. This is for applications that cannot keep connections long (such as web processes that connect on every request).
Connection and session. One row of V$SESSION is a session, and one row of V$PROCESS is a server process. With a dedicated server the two are one to one, but they are not the same thing. A connection can exist with no session, and one connection can create several sessions.
Connection cost. Connecting to a dedicated server means creating an operating system process and allocating a PGA, which is expensive. When many applications connect and disconnect on every request, the listener and process creation become a bottleneck (a logon storm). The baseline is to keep connections alive with an application server connection pool, and if that is not possible, use DRCP.
| Limit | Setting |
|---|---|
| Number of processes and sessions | PROCESSES, SESSIONS. Exceeding them raises ORA-00020, ORA-00018 |
| Sessions per user, idle time | SESSIONS_PER_USER, IDLE_TIME in a profile (when RESOURCE_LIMIT = TRUE) |
| Ending idle sessions | MAX_IDLE_TIME (minutes, default 0 = none) |
| Detecting dead connections | SQLNET.EXPIRE_TIME in sqlnet.ora (minutes) |
Cursor Structure
Figure. Shared cursors and session cursors
block-beta
columns 6
t1["Library cache in the SGA shared pool: used by all sessions together"]:6
pc["Parent cursor<br/>SQL text, SQL_ID"]:2 c0["Child cursor 0<br/>execution plan A, execution environment"]:2 c1["Child cursor 1<br/>execution plan B, different environment"]:2
u1<["Points to child cursor 0"]>(up):3 u2<["Points to child cursor 0"]>(up):3
t2["PGA of session 1"]:3 t3["PGA of session 2"]:3
s1["Session cursor<br/>bind value 101, read position"]:3 s2["Session cursor<br/>bind value 202, read position"]:3
class t1,t2,t3 plain
class pc meta
class c0,c1 data
class s1,s2 slot
class u1,u2 plain
Diagram description: The upper part is shared, and the lower part exists per session.
- A
Parent cursorexists once per SQL text. The hash of the text is theSQL_ID. One different character, one different space, or a different letter case makes a different parent cursor. - A
Child cursorholds the execution plan for that text and the environment in which the plan was built (optimizer settings, the type and length of bind variables, the actual objects the names point to). Even with the same text, a different environment creates a separate child cursor. For example, when two users query tables of the same name in their own schemas, there is one parent and two children. One row ofV$SQLis one child cursor. - A
Session cursoris the private SQL area in the session's PGA, and it holds the bind values for this execution and how far the session has read. The two sessions in the figure have different bind values but point to the sameChild cursor 0, so the execution plan was built only once.
Kinds of parsing
Figure. The path a statement takes when it arrives
flowchart TB
A["Statement execution request"] --> B{"Has the application<br/>kept the cursor open?"}
B -->|"Yes"| X["Execute without parsing<br/>only change the bind values"]
B -->|"No"| C{"Is it in the<br/>session cursor cache?"}
C -->|"Yes"| Y["Session cursor cache hit<br/>skip the library cache search"]
C -->|"No"| D["Syntax and semantic check<br/>search the library cache by text hash"]
D --> E{"Is there a usable<br/>child cursor?"}
E -->|"Yes"| S["Soft parse<br/>use the existing plan"]
E -->|"No"| H["Hard parse<br/>optimize, build the execution plan, load into the shared pool"]
Y --> R["Execute"]
S --> R
H --> R
X --> R
Diagram description: The further down the path, the more expensive it is.
- No parse. If the application does not close the cursor (the statement handle) and runs it again with only the bind values changed, there is no parse request at all. This is the cheapest.
- Session cursor cache hit. The application closed the cursor, but the session keeps up to
SESSION_CACHED_CURSORSclosed cursors cached. When the same statement comes again, it reaches the shared cursor directly without searching the library cache. - Soft parse. This is the case where Oracle checks syntax and semantics (objects, privileges), searches the library cache by the text hash, and finds a usable child cursor. It does no optimization, but it must take a library cache mutex, so it also becomes a contention point when many sessions run concurrently.
- Hard parse. No matching child cursor exists, so the optimizer builds a new plan and allocates and loads memory in the shared pool. It uses a lot of CPU and holds shared pool latches for a long time.
Bind variables
-- Literals: different text for each value, a hard parse for each value
SELECT * FROM orders WHERE ord_id = 1001;
SELECT * FROM orders WHERE ord_id = 1002;
-- Bind variable: one text, one hard parse
SELECT * FROM orders WHERE ord_id = :id;
With literals, every different value creates a new parent cursor. Hard parses repeat, cursors used only once fill the shared pool and push out other cursors, and in severe cases the shared pool fragments and ORA-04031 occurs. In OLTP, using bind variables is the rule.
| Topic | Description |
|---|---|
CURSOR_SHARING = FORCE | When the application cannot be fixed, the server replaces literals with bind variables such as :SYS_B_0 so they can be shared |
| Bind peeking | At hard parse time, the plan is chosen by looking at the bind value at that moment. A plan that suits that value can be bad for other values |
| Adaptive cursor sharing | Marks statements whose selectivity varies greatly with the value (IS_BIND_SENSITIVE), and if execution statistics are bad, creates separate child cursors per selectivity range (IS_BIND_AWARE) |
| Why child cursors multiply | Each column of V$SQL_SHARED_CURSOR tells why sharing failed (a difference in bind length, a difference in optimizer settings, and so on) |
| Plan pinning | SQL plan baselines (SPM) make the optimizer use only accepted plans. OPTIMIZER_USE_SQL_PLAN_BASELINES defaults to TRUE |
Invalidation and aging out
- When DDL runs on an object a cursor references, or statistics are gathered again, the cursor becomes invalid and is hard parsed at the next execution. By default
DBMS_STATSdoes not invalidate cursors all at once; it spreads the invalidation over a period of time. This avoids a burst of hard parses at a single moment. - When the shared pool runs short, Oracle ages out the cursors that have gone unused longest. The number of times an aged-out cursor was needed again and loaded again is
V$LIBRARYCACHE.RELOADS. ALTER SYSTEM FLUSH SHARED_POOLdiscards all cursors. To discard only one statement, useDBMS_SHARED_POOL.PURGE.
Reading Results Through a Cursor
Oracle does not build the whole result of a SELECT at once. When a cursor is opened, the SCN at that moment is fixed, and each FETCH runs only as much as needed and returns rows.
| Topic | Description |
|---|---|
| Read consistency | Reads the data as of the moment the cursor was opened. If a cursor stays open and is read for a long time, the needed Undo can disappear and ORA-01555 can occur |
| Array fetch | Receives several rows per round trip. SQL*Plus ARRAYSIZE defaults to 15, and the JDBC default fetch size is 10. A small value means more round trips |
| Fetching across a commit | The cursor stays valid after a commit. But a FOR UPDATE cursor loses its locks on commit, so the next fetch raises ORA-01002 |
| PL/SQL explicit cursor | CURSOR c IS …, OPEN, FETCH, CLOSE. FOR rec IN c LOOP opens and closes automatically and fetches 100 rows at a time internally |
| Bulk fetch | FETCH c BULK COLLECT INTO … LIMIT n |
| REF CURSOR | A variable that points to an open cursor (SYS_REFCURSOR). A procedure opens it and hands it to the client |
| Cursor cache in PL/SQL | Static SQL inside PL/SQL stays in the session cursor cache after closing and is reused |
| Open cursor limit | OPEN_CURSORS per session. If the application does not close statement handles, ORA-01000 occurs |
Result Cache
| Kind | Location | Behavior |
|---|---|---|
| Server result cache (SQL) | Shared pool | Stores the result rows of a query with the /*+ RESULT_CACHE */ hint (or a query on a table marked RESULT_CACHE (MODE FORCE)). The same query with the same bind values returns without executing |
| PL/SQL function result cache | Shared pool | The return value per argument of a function declared with RESULT_CACHE |
| Client result cache | Client process (OCI) | CLIENT_RESULT_CACHE_SIZE (default 0 = off) |
When a referenced table changes, the result cache invalidates every result that depends on that table. It suits small results that are read often and change rarely (code table lookups, aggregates), and on frequently updated tables the invalidation cost outweighs the gain. The size is RESULT_CACHE_MAX_SIZE, and the maximum share for one result is RESULT_CACHE_MAX_RESULT (default 5%).
In the Sandbox
These are values seen in this site's Oracle sandbox (23.26.4).
| Item | Value |
|---|---|
cursor_sharing / open_cursors / session_cached_cursors | EXACT / 300 / 50 |
Child cursors in V$SQL / distinct SQL_ID | 765 / 401 |
| Shared memory of those cursors | 39.5MB (of a 432MB shared pool) |
Library cache SQL AREA | Of 177,107 gets, 150,612 hits (85%); of 1,888,966 pins, 1,822,364 hits (96%) |
Reloads (RELOADS) / invalidations (INVALIDATIONS) | 10,491 / 4,357 |
result_cache_mode / result_cache_max_size | MANUAL / 8,126,464 bytes |
| DRCP default pool | SYS_DEFAULT_CONNECTION_POOL, INACTIVE (min 4, max 40) |
| Server type of sessions | All DEDICATED |
Configuration and Inspection
-- Shared cursors: statements with many parses relative to executions, statements with many child cursors
SELECT sql_id, child_number, executions, parse_calls, loads, invalidations, plan_hash_value,
is_bind_sensitive, is_bind_aware, SUBSTR(sql_text, 1, 60) AS sql_text
FROM v$sql ORDER BY parse_calls DESC FETCH FIRST 10 ROWS ONLY;
SELECT sql_id, version_count FROM v$sqlarea WHERE version_count > 10 ORDER BY version_count DESC;
-- Find statements that differ only in literals: several SQL_IDs under one FORCE_MATCHING_SIGNATURE
SELECT force_matching_signature, COUNT(*) AS n
FROM v$sql WHERE force_matching_signature <> 0
GROUP BY force_matching_signature HAVING COUNT(*) > 20 ORDER BY n DESC;
-- Parse statistics
SELECT name, value FROM v$sysstat
WHERE name IN ('parse count (total)', 'parse count (hard)', 'session cursor cache hits', 'execute count');
-- Open cursors per session
SELECT s.sid, s.username, COUNT(*) AS open_cursors
FROM v$open_cursor oc JOIN v$session s ON s.saddr = oc.saddr
GROUP BY s.sid, s.username ORDER BY open_cursors DESC;
-- Library cache hits and reloads
SELECT namespace, gets, gethits, pins, pinhits, reloads, invalidations
FROM v$librarycache WHERE namespace = 'SQL AREA';
-- Result cache
SELECT name, value FROM v$result_cache_statistics;
- Look at the hard parse ratio as
parse count (hard)÷parse count (total). In OLTP, a high value points to literal SQL. - To see a cursor's actual plan, use
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR('<sql_id>', <child_number>)).
Comparison with Other DBMSs
| Oracle | PostgreSQL | MySQL | SQL Server | KDBS | |
|---|---|---|---|---|---|
| Execution plan cache | Shared pool (all sessions) | Session-local, prepared statements only | None | Plan cache (all sessions) | None. Caches only the join order |
| Cache key | Text hash (SQL_ID) + environment | Prepared statement name | Text hash + SET options | Statement shape (fetch_id) | |
| Automatic literal replacement | CURSOR_SHARING = FORCE | None | None | Simple and forced parameterization | Literals excluded from the shape calculation |
| Plans by value | Bind peeking, adaptive cursor sharing | Custom plan and generic plan | Optimized on every execution | Parameter sniffing, PSP optimization | Compiled on every execution |
| Result cache | Server and client result cache | None | None (removed in 8.0) | None | None |
The full comparison is in DBMS Architecture at a Glance.
NOTE Defaults and view columns can vary by version. The detailed behavior of adaptive cursor sharing and the result cache has been adjusted from version to version.
Related pages
- DBMS Architecture at a Glance
- Oracle Database
- Oracle memory and process structure
- Oracle Buffer Cache
- Oracle Undo
- Oracle TM and TX locks
- PostgreSQL connections, cursors, and SQL cache
- MySQL Connections, Cursors, and SQL Cache
- SQL Server Connections, Cursors, and Plan Cache
- KDBS connections, portals, and statement cache