Does the order of conditions in a WHERE clause affect MySQL performance?

前端 未结 8 613
长发绾君心
长发绾君心 2020-11-29 06:10

Say that I have a long, expensive query, packed with conditions, searching a large number of rows. I also have one particular condition, like a company id, that will limit t

8条回答
  •  自闭症患者
    2020-11-29 07:01

    Here is a demo showing the order of WHERE clause conditions can make a difference due to short-circuiting. It runs the following queries:

    -- query #1
    SELECT myint FROM mytable WHERE myint >= 3 OR myslowfunction('query #1', myint) = 1;
    
    -- query #2
    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 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.

    So IMO the answer to the question:

    Does the order of conditions in a WHERE clause affect MySQL performance?

    is "Sometimes it can do."

提交回复
热议问题