Caching Function Results with SELECT FROM DUAL
In Oracle, when you use a PL/SQL function in the SELECT list or the WHERE clause, the function is called once per row. Reading 1 million rows means 1 million calls, and each call carries the cost of a context switch between the SQL engine and the PL/SQL engine. If the input has few distinct values, simply wrapping the function call in a scalar subquery such as (SELECT f(x) FROM dual) can cut the number of calls sharply. This works because Oracle keeps the scalar subquery's input values and results in memory during the statement's execution, and when the same input arrives again, it returns the kept result without running the subquery. This feature is called scalar subquery caching.
-- Called once per row
SELECT o.ord_id, get_grade_name(c.grade) AS grade_nm FROM orders o JOIN customers c ON c.cust_id = o.cust_id;
-- When the same grade comes again, the result is taken from the cache
SELECT o.ord_id, (SELECT get_grade_name(c.grade) FROM dual) AS grade_nm FROM orders o JOIN customers c ON c.cust_id = o.cust_id;
Summary
| Item | Description |
|---|---|
| Where it applies | PL/SQL function calls in the SELECT list, the WHERE clause, and other places where an expression is allowed |
| How to change | f(col) → (SELECT f(col) FROM dual) |
| Cache scope | During one execution of the statement. Not shared with the next execution or other sessions |
| Cache key | The outer query's column value that the subquery references (c.grade in the example above) |
| Cache size | A hash table. The size is the hidden parameter _query_execution_cache_max_size (131,072 bytes in the sandbox) |
| Large benefit | Few distinct input values, and the function is expensive (for example, a function that runs SQL inside) |
| Small benefit | Nearly all input values differ. Values that cause hash collisions. Row order changes the value often |
| Cases where the result can differ | The function reads data that changes during execution, or has SYSDATE, sequences, or side effects (such as writing a log) |
How it works
Figure. What the scalar subquery cache does for each row
flowchart TB
R["One row of the outer query<br/>e.g. status = 'PAID'"] --> L{"Is the input the same<br/>as the previous row's"}
L -->|"Yes"| HIT1["Use the previous result as is<br/>No function call"]
L -->|"No"| H{"Is this input<br/>in the hash table"}
H -->|"Yes"| HIT2["Use the stored result<br/>No function call"]
H -->|"No"| CALL["Run the subquery<br/>Call the function"]
CALL --> S{"Is that hash slot<br/>empty"}
S -->|"Yes"| PUT["Store the input and result"]
S -->|"No, another value occupies it"| SKIP["Do not store<br/>Called again next time"]
Diagram notes: each row of the outer query goes down from the top.
- First, it compares with the previous row's input value. If they are the same, it uses the previous result. So if rows arrive in an order where the same value repeats consecutively, almost no calls occur even without a hash table.
- If they differ, it looks in the hash table. If found, it uses the stored result.
- If not found, it runs the subquery to call the function and puts the result in that value's slot in the hash table. If another value already occupies that slot, it does not store (hash collision). From then on, this value is called every time except when it equals the previous row's.
- The hash table has a fixed size, so when the input has many distinct values, more values cannot be stored and the call count approaches the row count again.
The cache is discarded when the statement ends. Running the same statement again starts from an empty cache. The hash function, the table size, and the collision handling are internal behavior that Oracle does not publish, so the figure above depicts behavior consistent with the measurements below.
The cache key is the outer query's column
The input value of the scalar subquery (SELECT f(mod(cust_id, 100)) FROM dual) is not mod(cust_id, 100) but the outer column cust_id that the subquery references. Even if the values passed to the function have 100 kinds, if cust_id has 60,000 kinds, the cache handles 60,000 keys. To pass fewer values, compute the reduced expression outside so that the subquery sees only its result.
-- The key is cust_id (many distinct values)
SELECT SUM((SELECT f(MOD(o.cust_id, 100)) FROM dual)) FROM orders o;
-- The key is m (100 distinct values)
SELECT SUM((SELECT f(v.m) FROM dual)) FROM (SELECT /*+ NO_MERGE */ MOD(cust_id, 100) AS m FROM orders) v;
In the sandbox, this change reduced the call count from 93,029 to 6,022 (table below). The keys dropped to 100, but because of hash collisions the count did not fall as low as 100.
Counting calls in the sandbox
The number of times the function was called is counted by adding 1 to the session's CLIENT_INFO inside the function. All measurements below were made on tune.orders in this site's Oracle sandbox (23.26.4), and the function was defined inside the statement with WITH FUNCTION, so no object was created in the database.
EXEC DBMS_APPLICATION_INFO.SET_CLIENT_INFO('0')
WITH FUNCTION f(p VARCHAR2) RETURN VARCHAR2 IS
BEGIN
DBMS_APPLICATION_INFO.SET_CLIENT_INFO(TO_NUMBER(SYS_CONTEXT('USERENV', 'CLIENT_INFO')) + 1);
RETURN p;
END;
SELECT SUM(LENGTH((SELECT f(status) FROM dual))) FROM tune.orders WHERE ord_id <= 100000
/
SELECT SYS_CONTEXT('USERENV', 'CLIENT_INFO') AS calls FROM dual;
In the first 100,000 rows of orders, status has 3 values (DONE 90,136 rows, PAID 6,901 rows, CANCELED 2,963 rows), and cust_id has 59,328 values.
| Statement | Rows | Distinct input values | Function calls |
|---|---|---|---|
f(status) | 100,000 | 3 | 100,000 |
(SELECT f(status) FROM dual) | 100,000 | 3 | 8,967 |
Same statement without the CANCELED rows | 97,037 | 2 | 2 |
Same statement without the PAID rows | 93,099 | 2 | 2,875 |
(SELECT f(status) FROM dual), fast full scan of ORDERS_X2 (an index with status as the first column) | 1,000,000 | 3 | 3 |
(SELECT f(status) FROM dual), full table scan | 1,000,000 | 3 | 89,750 |
(SELECT f('X') FROM dual) (constant) | 100,000 | 1 | 1 |
(SELECT f(grade) FROM dual), tune.customers | 100,000 | 3 | 3 |
f(cust_id) | 100,000 | 59,328 | 100,000 |
(SELECT f(cust_id) FROM dual) | 100,000 | 59,328 | 93,029 |
Same statement, input sorted by cust_id | 100,000 | 59,328 | 59,328 |
(SELECT f(MOD(cust_id, 100)) FROM dual) | 100,000 | The key is cust_id | 93,029 |
MOD(cust_id, 100) AS m computed first in an inline view, (SELECT f(v.m) FROM dual) | 100,000 | 100 | 6,022 |
Three things to read from the table.
- With few distinct values, the benefit is mostly large. For
customers.gradeand the constant input, the function was called only as many times as there are distinct values. - Hash collisions are unpredictable. With the same 3
statusvalues, there were 8,967 calls. WithoutCANCELEDit was 2, and withoutPAIDit was 2,875 (close to the row count ofCANCELED), soDONEandCANCELEDappear to have collided over the same slot in the hash table. Even with only 3 values, if they collide, that value is called almost every time. - Row order changes the result. With the same 3 values and the same 1 million rows, the plan that read an index sorted by
statushad the same values arrive consecutively and gave 3 calls, while the full table scan gave 89,750. Whencust_idwas also passed in sorted order, calls were only as many as the distinct values (59,328), regardless of collisions. If the execution plan changes, the benefit changes too.
Time
The entire 2 million rows of orders, 3 status values, and the lightest case where the function just returns its value.
| Statement | Function calls | Time |
|---|---|---|
SUM(LENGTH(status)) without a function | 0 | 0.08 s |
f(status) | 2,000,000 | 3.10 s |
(SELECT f(status) FROM dual) | 180,227 | 0.50 s |
Even a function that does nothing took 3 seconds for 2 million calls when called per row. Most of this cost is not the computation inside the function but the switch between SQL and PL/SQL. For a function that runs SQL again inside (such as looking up a code name), one call is much more expensive and the difference grows.
Comparison with other methods
| Method | How to use | Cache scope | Characteristics |
|---|---|---|---|
| Scalar subquery caching | (SELECT f(x) FROM dual) | One execution of the statement | No need to change the function definition. The benefit depends on the number of distinct values, collisions, and row order |
DETERMINISTIC | DETERMINISTIC in the function declaration | Within one fetch call | A promise to Oracle that the same input gives the same result. It works per fetch, so the benefit is tied to the fetch size (ARRAYSIZE) |
| Function result cache | RESULT_CACHE in the function declaration | Instance (all sessions), SGA shared pool | Reused across statements and sessions. Invalidated when a table the function reads changes. A loss if updates are frequent |
PRAGMA UDF, WITH FUNCTION (from 12c) | PRAGMA UDF on the function, or defining the function inside the statement | Not a cache | The call count stays the same, but the switch cost of each call is reduced |
| Rewrite as a join | Turn the lookup the function did into a join or CASE | Not applicable | Fastest if the function is a simple lookup. The optimizer can choose the whole plan |
When a DETERMINISTIC function was used on the same 100,000 rows in the sandbox, the call count was 99,986 for a statement that finished the aggregation in one fetch, and 7,611 for a statement that fetched 100 rows at a time to receive the 100,000 rows. It had almost no effect on a statement that finishes inside the server, like an aggregation.
Cautions
- Do not use it for functions whose result changes. Caching assumes "the same input gives the same result". If the function uses
SYSDATE, a sequence, or a package variable, or reads a table that can change during statement execution, the result can differ from before the wrapping. SQL makes no promise about how many times it calls a function, so even an unwrapped query must not depend on the call count. - Side effects disappear. If the function writes a log or increments a counter, that work shrinks by as much as the calls do. The measurement above uses exactly this property.
- Measure the effect. As in the table above, the same statement varied from 3 to 90,000 calls depending on values and execution plan. After wrapping, check the actual call count or time. In
DBMS_XPLAN.DISPLAY_CURSOR(..., 'ALLSTATS LAST'),Startson theFAST DUALline is the number of times the subquery actually ran. - SQL inside the function shows up as recursive calls. If the function runs SQL, you can also check the call count from that SQL's
EXECUTIONSinV$SQL. - First check whether the function is really needed. If the function only looks up one code table row, a join is fastest, and the optimizer can choose the whole plan together. Scalar subquery caching is for when the function cannot be eliminated.
NOTE The size of the hash table and its collision handling are not published behavior, so they may differ by version. The figures in this document were measured in the Oracle AI Database 26ai Free (23.26.4) sandbox.