I was optimizing one of horrible views we have and it came as surprise that one of subselects with CASE
statements was running faster than LEFT JOIN
with OR
. Original view is substantially bigger but parts that I am interested in can be boiled down to following queries
SELECT CASE
WHEN tdcurr.productid = 1 THEN (SELECT addressid
FROM address a
WHERE a.customerid = tm.customerid
AND a.addressid =
tdcurr.addressid
AND a.addresstypeid = 3)
WHEN tdcurr.productid = 2 THEN (SELECT addressid
FROM address a
WHERE a.customerid = tm.customerid
AND a.addressid =
tdcurr.addressid
AND a.addresstypeid = 4)
END AS t_buyselladdressid
FROM vleaf_transactiondetail_all tdcurr
inner join transactionmain tm
ON tm.transactionid = tdcurr.transactionid
Execution plan
while one with join is consistently slower
SELECT bsaddr.addressid AS t_buyselladdressid
FROM vleaf_transactiondetail_all tdcurr
inner join transactionmain tm
ON tm.transactionid = tdcurr.transactionid
left outer join address bsaddr
ON tm.customerid = bsaddr.customerid
AND bsaddr.addressid = tdcurr.addressid
AND ( ( tdcurr.productid = 1
AND bsaddr.addresstypeid = 3 )
OR ( tdcurr.productid = 2
AND bsaddr.addresstypeid = 4 ) )
Execution Plan
Why would this be the case?