Skip to content
Advertisement

Oracle Case Statement and efficency

I have a piece of my Oracle Query i need to optimize a little

select
case 
    when SUM(dnl.quantity) = line.quantity then 1 
    when SUM(dnl.quantity) < line.quantity then 0 
    when SUM(dnl.quantity) > line.quantity then 2 
end
from mytable dnl

line.quantity comes out from other part o query, for this example is not needed i think. I would like to calculate only once SUM(dnl.quantity) instead ad every iteraciotn, somethink like

select
case SUM(dnl.quantity)
    when line.quantity then 1 
    when < line.quantity then 0 
    when > line.quantity then 2 
end
from mytable dnl

But obviously this give error at the second and 3rd WHEN

Advertisement

Answer

You are over-optimizing. The Oracle compiler can decide how many times it wants to evaluate sum(dnl.quantity). However, the data movement is usually much more expensive than the calculation of aggregations on a single column.

That said if you are really concerned about this, you can use sign():

(case sign(sum(dnl.quantity) - line_quantity)
     when 0 then 1 
     when -1 then 0 
     when 1 then 2 
 end)

Or to be more inscrutible:

sign(sum(dnl.quantity) - line_quantity) + 1
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement