0
votes

This is an excerpt from a large SQL statement. PS alias is a table in FROM clause of parent SQL statement

WHERE 
   (
      ISNULL(PS.HRKY,'')='' 
      OR 
      ( 
        ISNULL(PS.HRKY,'')<>''  AND  EXISTS  
            (
            SELECT 1 
            FROM SCHEME B 
            WHERE 
                  PS.COMPANY=B.COMPANY AND 
                  PS.PBS_MP_CODE=B.MP_CODE AND 
                  PS.PBS_SEQID=B.SEQ_ID AND 
                  B.FIELD_COMB LIKE '%CAT%' AND 
                  B.VALUE_COMB LIKE '%'+@catName+'%' 
            )
      )
  )
  AND 
  ( 
    /*repeated with different columns*/ 
  )

This is one of the 8 conditions that the where clause has of the larger statement.

My question is can I somehow short circuit the conditions without affecting their outcome to reduce computation?

Unlike programming languages such as Java and C#, SQL does not use any short-circuiting rules. This means here that the SQL Server engine may choose to evaluate any of the ANDed conditions in your WHERE clause first, and the others in any order, if it deems it be beneficial for the execution plan. - Tim Biegeleisen
I was trying to solve it using logic algebra. if the current condition is X OR (!X AND Y) then it seems equivalent to X OR Y as both yield the same result. I'm not sure if that effects the performance in SQL Server - Simple Fellow
Unless you actually have a performance issue I wouldn't attempt to optimise it. - Dale K
there are 8 such conditions. I have written only one. currently the execution plan shows that only this SQL statement (whose where clause i have here) takes 91% time in SP. so yes there is performance issue. - Simple Fellow
Magnitude makes a difference. Is it 91% of 1ms, so not worth worrying about, or 91% of 60s? You haven't shown us a query plan, so I'm only guessing, but consider that execution planner may be choosing to execute this subquery on an RBAR (Row By Agonizing Row) basis when it may be better to restructure it as a left join over a query that's grouping by B.MP_CODE and B.SEQ_ID to use as join conditions. Is there any way to remove the '%SOMETHING%' conditions because they basically neuter any indexes on those columns - even 'SOMETHING%' would be an improvement. - AlwaysLearning