cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Slow case statement evaluation comparing values from two tables

patrickbachmann
Active Contributor
0 Likes
1,259

Hi folks,

We have an SQL type calculation view that is performing badly.  Upon analyzing the visual plan we have found the root of the problem due to a case statement that is simply evaluating two tables and if a field is null in one table then choose the other alternate table field;  something like this;

select

case when a.Customer IS NULL THEN

b.Customer

else

a.Customer

End

As TheCustomer

from table1 a join table2 b on a.XYZ = b.XYZ

etc

If we take the case statement away and simply return both values, the query runs very fast around 2 seconds.  ie: something like this;

select

a.Customer as Customer1,

b.Customer as Customer2

from table1 a join table2 b on a.XYZ = b.XYZ

etc

But doing the case evaluation between the two field values bumps the execution time up to more than 60 seconds!

Has anybody experienced this and do you have any alternative suggestions to achieve this sort of thing?  We have also tried doing a second pass and putting the case evaluation OUTSIDE the original select statement and there is some big improvement yet still not satisfactory.  ie: something like this;

select

case when a.Customer IS NULL THEN

b.Customer

else

a.Customer

End

As TheCustomer from

( select

a.Customer as Customer1,

b.Customer as Customer2

from table1 a join table2 b on a.XYZ = b.XYZ

etc)

Thanks,

-Patrick

View Entire Topic
former_member182302
Active Contributor
0 Likes

Did you try COALESCE as well?

Regards,

Krishna Tangudu

lbreddemann
Active Contributor
0 Likes

Spot on!

COALESCE would be the way to do it. The only thing you have to take care of is to check whether tie values are resolved in your interest.

However, using CASE, COALESCE, IFNULL... in the projection list will always add a lot of execution time as these expressions need to be evaluated on the whole set of returned records.

- Lars