In mysql, does the order of the WHERE clauses affect the time that it takes the server to process the query?
I know that the queries are compiled and optimized, but I don’t know if that optimization changes the order of the WHERE clauses so in a hypothetic case it will take less time to process a query that first selects the results with an integer than if it starts with a string index for example.
WHERE a = 2 AND b = 'Wiliam'
- 1: Search in 200 items and find 20 results with value a = 2
- 2: Search in 20 items and find 1 result with b = Wiliam
That
WHERE b = 'Wiliam' AND a = 2
- 1: Search in 200 items and find 20 results with value b = Wiliam
- 2: Search in 20 items and find 1 result with a = 2
Will it be faster if we start searching a integer indexed column? Does mysql know which clause has a worse index to do the second search?
Thanks.
The optimizer can and often will change the order of the evaluation of predicates to better take advantage of the indexes. MySQL keeps statistics on each index and it will use those to choose which index is likely to be fastest. There are no easy rules about which index will be chosen: it is free to choose different indexes depending on the data in the database and the values you are looking for.
In the case where there are no indexes it can make a difference, but it is rarely worth worrying about:
Test data: