Is the SQL WHERE clause short-circuit evaluated?

前端 未结 14 2654
时光取名叫无心
时光取名叫无心 2020-11-22 04:31

Are boolean expressions in SQL WHERE clauses short-circuit evaluated ?

For example:

SELECT * 
FROM Table t 
WHERE @key IS NULL OR (@key IS NOT NULL          


        
14条回答
  •  一个人的身影
    2020-11-22 04:50

    i don't know about short circuting, but i'd write it as an if-else statement

    if (@key is null)
    begin
    
         SELECT * 
         FROM Table t 
    
    end
    else
    begin
    
         SELECT * 
         FROM Table t 
         WHERE t.Key=@key
    
    end
    

    also, variables should always be on the right side of the equation. this makes it sargable.

    http://en.wikipedia.org/wiki/Sargable

提交回复
热议问题