Is the SQL WHERE clause short-circuit evaluated?

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

    Just stumbled over this question, and had already found this blog-entry: http://rusanu.com/2009/09/13/on-sql-server-boolean-operator-short-circuit/

    The SQL server is free to optimize a query anywhere she sees fit, so in the example given in the blog post, you cannot rely on short-circuiting.

    However, a CASE is apparently documented to evaluate in the written order - check the comments of that blog post.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题