Is the SQL WHERE clause short-circuit evaluated?

前端 未结 14 2647
时光取名叫无心
时光取名叫无心 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 05:05

    Below a quick and dirty test on SQL Server 2008 R2:

    SELECT *
    FROM table
    WHERE 1=0
    AND (function call to complex operation)
    

    This returns immediately with no records. Kind of short circuit behavior was present.

    Then tried this:

    SELECT *
    FROM table
    WHERE (a field from table) < 0
    AND (function call to complex operation)
    

    knowing no record would satisfy this condition:

    (a field from table) < 0
    

    This took several seconds, indicating the short circuit behavior was not there any more and the complex operation was being evaluated for every record.

    Hope this helps guys.

提交回复
热议问题