Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

oracle: decode and subquery select result

I have a oracle query and part of it is calculating some value using DECODE. For example:

SELECT ..., 
      (SELECT DECODE((SELECT 23 FROM DUAL), 
                      0, null,
                     (SELECT 23 FROM DUAL))  
         FROM DUAL) 
  FROM ...

Here the value "23" gets calculated at runtime, and it's quite complicated joins - multiple tables, uses PARTITION BY etc. So I want to avoid executing the same subquery if the value is not "0". Is there any way to write something like this

SELECT ..., 
       (SELECT DECODE ((SELECT 23 FROM DUAL) as test, 
                        0, null,
                       test)  
         FROM DUAL) 
  FROM ...
like image 470
hanumant Avatar asked Jun 01 '11 04:06

hanumant


2 Answers

Will this work for you? I've just moved the "23" to an inline table with a descriptive alias.

select ..., 
  (
   select 
     decode ( 
            computed_value.val, 
            0, null,
            computed_value.val
            )  
   from
     (select 23 as val from dual) computed_value
  )
from
  ...

A CASE statement might also add clarity, as in:

select
  ...
 ,case when computed_value.val = 0
       then null
       else computed_value.val
       end as my_field
from
  (select 23 as val from dual) computed_value
  ...
like image 133
JosephStyons Avatar answered Sep 20 '22 15:09

JosephStyons


Or:

WITH q AS (
SELECT 23 test, 16 test2 FROM dual
)
SELECT ... 
     , DECODE(q.test, 0, NULL, q.test) value
     , CASE WHEN q.test2 = 0 THEN NULL 
            WHEN q.test2 = 16 THEN 1
            ELSE q.test2
       END another_value
  FROM q, ...

Lets you use the query "q" throughout your main select, where ever a subquery is allowed. Called the WITH clause, or Common Table Expression, or Subquery Factoring. Read more about it at Oracle-Base.com.

like image 44
DCookie Avatar answered Sep 21 '22 15:09

DCookie