views:

53

answers:

2

Suppose I want to query a table based on multiple WHERE clauses.

Would either of these statements be faster than the other?

  SELECT * 
    FROM table 
   WHERE (line_type='section_intro' OR line_type='question') 
     AND (line_order BETWEEN 0 AND 12) 
ORDER BY line_order";

...or:

  SELECT * 
    FROM table 
   WHERE (line_order BETWEEN 0 AND 12) 
     AND (line_type='section_intro' OR line_type='question') 
ORDER BY line_order;

I guess what it would come down to is whether the first one would select more than 12 records, and then pare down from there.

+2  A: 

No, the order does not matter. Query optimizer is going to estimate all conditions separately and decide on the best order based on what indexes are applicable / size of targeted selection / etc...

ChssPly76
Excellent, that's what I kind of thought but figured it would be good to know for future reference.Thanks!
javanix
A: 

It depends on your indexes. If you have a multi- index on (line_type, line_order), the first query is faster. If you have an index on (line_order, line_type), the second one is faster. This is because for multi-column primary keys, MySQL can only do the comparisons in order. Otherwise, there is no difference.

HTH -

Chris

Chris Morgan
This is incorrect. Both queries are going to be exactly the same on either index; which one of the **indexes** will make queries perform faster depends on how many matching rows are in the table / index. For example, if all (or vast majority) of rows in the table have `line_type` set to either `section_intro` or `question`, index defined on (line_type, line_order) would not be used at all.
ChssPly76