Sub topic 13
Performance Options: DETERMINISTIC, RESULT_CACHE, and NOCOPY
This chapter assumes you can already write stored functions and procedures, use IN, OUT, and IN OUT parameters, and call functions from SQL. Here you will learn three options that change how Oracle runs a subprogram. They help in specific situations and can cause wrong results or no gain when misused.
| Option | Applies to | What it changes | Main risk |
|---|---|---|---|
| `DETERMINISTIC` | Functions | Lets Oracle reuse results and permits function-based indexes | A false promise gives wrong results |
| `RESULT_CACHE` | Functions | Stores results in shared memory across sessions | Memory use, invalidation churn, stale-looking results |
| `NOCOPY` | OUT and IN OUT parameters | Passes by reference instead of by copy | Partial changes survive an error |
DETERMINISTIC: promising repeatable results
A function is deterministic when the same input values always produce the same return value. Declaring DETERMINISTIC is a promise to Oracle. The database does not check it.
CREATE OR REPLACE FUNCTION normalize_phone (
p_phone IN VARCHAR2
) RETURN VARCHAR2
DETERMINISTIC
IS
BEGIN
RETURN REGEXP_REPLACE(p_phone, '[^0-9]', '');
END normalize_phone;
/The promise gives you two things:
- Reuse inside one statement. When a query calls the function repeatedly with the same arguments, Oracle may skip the repeat calls. This is an optimization, not a guarantee, so never rely on how many times the function runs.
- Eligibility for indexes and similar structures. A function-based index, a virtual column, or a materialized view used for query rewrite can only use a function that is declared
DETERMINISTIC.
CREATE INDEX emp_phone_norm_ix
ON employees (normalize_phone(phone_number));
SELECT employee_id, phone_number
FROM employees
WHERE normalize_phone(phone_number) = '5151234567';The index stores the computed values. If the function later returned different values for the same input, the stored entries would no longer match what the function returns, and queries would give wrong answers.
Changing a deterministic function that an index uses is risky. The existing index entries were built with the old logic. After such a change, rebuild the index.
RESULT_CACHE: sharing results across sessions
RESULT_CACHE stores a function's return value in the result cache, a region of the shared pool in the SGA. The next call with the same arguments, from any session, gets the stored value without running the function body. This suits functions that are expensive, called often with a small set of argument values, and based on data that rarely changes, such as lookup tables.
CREATE OR REPLACE FUNCTION get_department_name (
p_department_id IN departments.department_id%TYPE
) RETURN departments.department_name%TYPE
RESULT_CACHE
IS
v_name departments.department_name%TYPE;
BEGIN
SELECT department_name
INTO v_name
FROM departments
WHERE department_id = p_department_id;
RETURN v_name;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
END get_department_name;
/Oracle finds the tables the function reads and records them as dependencies. When a transaction commits a change to one of those tables, Oracle invalidates the cached results that depend on it. In Oracle 11g Release 1 you had to list the tables with RELIES_ON. From 11.2 onward this is automatic, and RELIES_ON is obsolete.
Checking that the cache works
Query the dynamic performance views. They need the right privileges, usually a DBA grant on the V$ views.
SELECT name, status, scan_count
FROM v$result_cache_objects
WHERE type = 'Result'
AND name LIKE '%GET_DEPARTMENT_NAME%';A rising SCAN_COUNT shows that later calls are being served from the cache. The package DBMS_RESULT_CACHE offers STATUS, MEMORY_REPORT, and FLUSH for inspecting and clearing the cache.
Restrictions and gotchas
- A cached function cannot have OUT or IN OUT parameters.
- IN parameters and the return type cannot be LOBs, REF CURSORs, or object types. Check the documentation for your release before caching a function that returns a collection or record.
- Pipelined table functions and functions defined in anonymous blocks cannot be cached.
- The cache has a fixed size, set by
RESULT_CACHE_MAX_SIZE. Oracle removes old entries when it is full. Many distinct argument values mean low reuse and constant churn. - A session with uncommitted changes to a dependent table does not use the shared cache for that function. It runs the body, so it sees its own uncommitted data.
- The cache knows only about database dependencies. A function that reads
SYSDATE, a context value, or a package variable can return a stale value from the cache, because none of those invalidates it.
RESULT_CACHE and DETERMINISTIC solve different problems. DETERMINISTIC is a promise about a function that does not read data. RESULT_CACHE is for functions that read tables, and Oracle tracks those tables. Do not combine the two on one function. A function that reads tables is not deterministic.
NOCOPY: passing large parameters by reference
By default, an IN parameter is passed by reference. OUT and IN OUT parameters are passed by value. Oracle works on a local copy and copies it back to the caller's variable only when the subprogram ends normally. This gives clean error behavior, since a failed call leaves the caller's variable unchanged. It is expensive for large collections or records, because the data is copied twice.
NOCOPY is a hint that asks Oracle to pass the parameter by reference. The subprogram then changes the caller's variable directly.
CREATE OR REPLACE PACKAGE bulk_demo AS
TYPE t_num_tab IS TABLE OF NUMBER INDEX BY PLS_INTEGER;
PROCEDURE double_all (p_values IN OUT NOCOPY t_num_tab);
PROCEDURE fail_midway (p_values IN OUT NOCOPY t_num_tab);
END bulk_demo;
/
CREATE OR REPLACE PACKAGE BODY bulk_demo AS
PROCEDURE double_all (p_values IN OUT NOCOPY t_num_tab) IS
BEGIN
FOR i IN 1 .. p_values.COUNT LOOP
p_values(i) := p_values(i) * 2;
END LOOP;
END double_all;
PROCEDURE fail_midway (p_values IN OUT NOCOPY t_num_tab) IS
BEGIN
p_values(1) := -1;
RAISE_APPLICATION_ERROR(-20002, 'Stopped after first change');
END fail_midway;
END bulk_demo;
/
DECLARE
v_values bulk_demo.t_num_tab;
BEGIN
v_values(1) := 10;
v_values(2) := 20;
bulk_demo.double_all(v_values);
DBMS_OUTPUT.PUT_LINE('After double_all: ' || v_values(1) || ', ' || v_values(2));
BEGIN
bulk_demo.fail_midway(v_values);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;
DBMS_OUTPUT.PUT_LINE('After failure: ' || v_values(1));
END;
/Run with SET SERVEROUTPUT ON. The last line prints -1. The failed call changed the caller's variable before it raised the error. Without NOCOPY, the caller's variable would still hold 20.
When NOCOPY is ignored or risky
- It is a hint, not a command. Oracle silently passes by value in some cases, including remote procedure calls, when the actual parameter is an element of an index-by table, and when the actual parameter needs an implicit conversion or has a constraint such as a NOT NULL or range subtype.
- Passing the same variable twice, or passing a variable that the subprogram can also reach as a global, creates aliasing. A change through one name is visible through the other, and results can depend on how Oracle chose to pass the parameter.
- Do not use it on small scalars. The copy is cheap, and you lose the all-or-nothing behavior.
- A function called from SQL cannot have OUT or IN OUT parameters at all, so
NOCOPYis only relevant to procedures and PL/SQL-only functions.
Choosing an option
Measure before and after. Use a representative data size, because these options matter only when the work is large or repeated.
Exercise
A function converts a country code to its tax rate by reading the TAX_RATES table. Your teammate marks it DETERMINISTIC so it can be used in a function-based index. What is wrong, and what option fits better if the goal is fewer table reads?
Show answer
The function reads a table, so its result can change when TAXRATES changes. DETERMINISTIC is a false promise, and an index built on it can return wrong results after a rate change. RESULTCACHE fits better, because Oracle tracks TAX_RATES as a dependency and invalidates the cached results when a change to it is committed. A function-based index is not possible on this function. Store the rate in a column, or join to the table in the query.
Exercise
A procedure has an IN OUT NOCOPY collection parameter. It updates the first 500 of 1000 elements and then raises an exception. What does the caller see in its variable, and what would it see without NOCOPY?
Show answer
With NOCOPY, the caller's variable already contains the 500 updated elements, because the procedure changed it directly. Without NOCOPY, the procedure worked on a copy that was discarded when the exception propagated, so the caller's variable keeps its original values.