Cursor reuse in PL/SQL static SQL

Background

In order that a SQL satement can be executed, it has to be parsed (checked for syntactic and semantic correctness) and the execution plan has to be calculated. All this costs computational resources.

To save on these costs, the Oracle instance maintains a system-wide LRU cache (aka the shared cursor cache) - exposed via v$sqlarea - of previously encountered SQL statements and appropriate derived information so that when the next SQL statement is submitted for parsing it is checked for match against the cached ones. (The definition of the criterea for a match is beyond the scope of this tutorial. Roughly speaking, the current statement must be both textually identical to its match candidate, famously to the extent of whitespace and upper/lower case identity, and the types of the bind variables must match.) When the current statement is matched, the stored derived information (parse tree, execution plan, etc) is reused and computational cost is saved.

Moreover, the above processing has to be done in the context of a cursor which itself has to be opened and associated with the SQL statement in question, again at some cost.

A given session might have one or several concurrently open cursors. Information on these, including the foreign key reference to v$sqlarea is exposed via v$open_cursor.

Advanced programmers using the "difficult" interfaces to cursor manipulation - eg OCI in a C programming environment or the Dbms_Sql package in a PL/SQL programming environment - typically code explicit, relatively elaborate approaches to minimize cursor costs. This cost-saving paradigm is described below.

Programmers whose requirements can be satisfied by static SQL in a PL/SQL programming environment enjoy the benefits of an implicit implementation of this cost-saving paradigm while writing simple, easy-to-maintain, code.

However, it is possible to subvert these implicit benefits by careless programing. This tutorial presents the conceptual background for understanding this and some guidelines for avoiding such mistakes.

Conclusion

Bryn Llewellyn, PL/SQL Product Manager, Oracle Corp
last updated 4-Jun-2003