Is the SQL WHERE clause short-circuit evaluated?

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

    Here is a demo to prove that MySQL does perform WHERE clause short-circuiting:

    http://rextester.com/GVE4880

    This runs the following queries:

    SELECT myint FROM mytable WHERE myint >= 3 OR myslowfunction('query #1', myint) = 1;
    SELECT myint FROM mytable WHERE myslowfunction('query #2', myint) = 1 OR myint >= 3;
    

    The only difference between these is the order of operands in the OR condition.

    myslowfunction deliberately sleeps for a second and has the side effect of adding an entry to a log table each time it is run. Here are the results of what is logged when running the above two queries:

    myslowfunction called for query #1 with value 1
    myslowfunction called for query #1 with value 2
    myslowfunction called for query #2 with value 1
    myslowfunction called for query #2 with value 2
    myslowfunction called for query #2 with value 3
    myslowfunction called for query #2 with value 4
    

    The above shows that a slow function is executed more times when it appears on the left side of an OR condition when the other operand isn't always true (due to short-circuiting).

提交回复
热议问题