Skip to Main Content

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Zilvinas.

Asked: May 23, 2017 - 9:23 am UTC

Last updated: May 24, 2017 - 1:26 am UTC

Version: Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production

Viewed 1000+ times

You Asked

Hello,

I have sql like this:
SELECT CASE a.x
         WHEN 'b' THEN (SELECT b.y FROM b WHERE b.id = a.b_id)
         WHEN 'c' THEN (SELECT c.y FROM c WHERE c.id = a.c_id)
         WHEN 'd' THEN (SELECT d.y FROM d WHERE d.id = a.d_id)
       END
  FROM a


The question is if all 3 subqueries inside case statement will be executed or only one that meets condtition?
From what I see in the execution plan it seems like all 3 subqueries will be executed.

and Connor said...

Its easy to prove that we dont run them all, eg

SQL> create table a ( x char(1));

Table created.

SQL> insert into a values ('b');

1 row created.

SQL>
SQL> create table b ( y int );

Table created.

SQL> insert into b values (1);

1 row created.

SQL>
SQL> SELECT CASE a.x
  2           WHEN 'b' THEN (SELECT b.y FROM b )
  3           WHEN 'c' THEN (SELECT y/0 FROM b )
  4           WHEN 'd' THEN (SELECT y/0 FROM b )
  5         END
  6    FROM a;

CASEA.XWHEN'B'THEN(SELECTB.YFROMB)WHEN'C'THEN(SELECTY/0FROMB)WHEN'D'THEN(SELECTY/0FROMB)END
-------------------------------------------------------------------------------------------
                                                                                          1

1 row selected.



No zero divide error.

Is this answer out of date? If it is, please let us know via a Comment