Oracle scalar subquery caching


The importance of being able to fully control executed SQL (using jOOQ, or plain JDBC) on large-scale systems becomes obvious every time you need to fine-tune your SQL queries for a specific RDBMS. In this case, we’re looking at Oracle and its miraculous scalar subquery caching mechanisms:

Usually, the context switch from SQL to PL/SQL and back is quite expensive for an average Oracle query, so we should normally omit putting stored functions as filtering, grouping, sorting criteria, even if they’re DETERMINISTIC. When we have large result sets, however, even functions in the query projection may turn out to be an execution plan nightmare. I recently raised the question on Stack Overflow, as I’m curious if there is any caching mechanism, that I could take advantage of for a concrete use-case:

http://stackoverflow.com/questions/7270467/is-there-a-pl-sql-pragma-similar-to-deterministic-but-for-the-scope-of-one-singl

And most interestingly, there are several. The accepted answer points to this very relevant article on Ask Tom’s Q/A:

http://www.oracle.com/technetwork/issue-archive/2011/11-sep/o51asktom-453438.html

Apparently, in scalar subqueries, function results may be cached! While this can be very useful for performance, it can also be very dangerous for consistency – as with any caching mechanism, but this one is highly implicit! So this will be cached:

-- my_function is NOT deterministic but it is cached!
select t.x, t.y, (select my_function(t.x) from dual)
from t

-- logically equivalent to this, uncached
select t.x, t.y, my_function(t.x) from t

Knowing this, I think I have to review quite a bit of SQL…

Tags: , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,628 other followers

%d bloggers like this: