HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Can I rely on functions being executed first in SQL

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
canrelysqlbeingexecutedfirstfunctions

Problem

Please consider the following script:

create or replace function f(p_limit in integer) return integer as
begin
set_global_context ('limit', p_limit);
return p_limit;
end;
/

create view v as
select level as val from dual connect by level

Can I rely on
f(x)` being executed before the context is read inside the view, as it has been in this test case run on 10.2?

Solution

No.

If you re-write your view with the context filtering against the where clause (instead of the connect by), you'll get the previously set value for the context:

create table t as 
 select rownum r from dual connect by level <= 10;

create or replace view v as 
  select r val from t where r <=sys_context('global_context','limit');

select f(2), v.* from v;

F(2) VAL
---- ---
   2   1 
   2   2 

select f(4), v.* from v;

F(4) VAL
---- ---
   4   1 
   4   2 

select f(4), v.* from v;

F(4) VAL
---- ---
   4   1 
   4   2 
   4   3 
   4   4


As the where clause is evaluated before the columns are selected, the value passed to the function isn't set until after the context is read. The location of the sys_context call in your query (select, where, group by, etc.) will affect exactly when this value is set.

Code Snippets

create table t as 
 select rownum r from dual connect by level <= 10;

create or replace view v as 
  select r val from t where r <=sys_context('global_context','limit');

select f(2), v.* from v;

F(2) VAL
---- ---
   2   1 
   2   2 

select f(4), v.* from v;

F(4) VAL
---- ---
   4   1 
   4   2 

select f(4), v.* from v;

F(4) VAL
---- ---
   4   1 
   4   2 
   4   3 
   4   4

Context

StackExchange Database Administrators Q#21644, answer score: 9

Revisions (0)

No revisions yet.