Suppose I have a MySQL query with two conditions:
SELECT * FROM `table` WHERE `field_1` = 1 AND `field_2` LIKE '%term%';
The first condition is obviously going to be a lot cheaper than the second, so I'd like to be sure that it runs first, limiting the pool of rows which will be compared with the LIKE clause. Do MySQL query conditions run in the order they're listed or, if not, is there a way to specify order?
Six Operations to Order: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY. By using examples, we will explain the execution order of the six most common operations or pieces in an SQL query. Because the database executes query components in a specific order, it's helpful for the developer to know this order.
No, the order of the WHERE clauses does not matter. The optimizer reviews the query & determines the best means of getting the data based on indexes and such.
The optimiser will evaluate the WHERE conditions in the order it sees fit.
SQL is declarative: you tell the optimiser what you want, not how to do it.
In a procedural/imperative language (.net, Java, php etc) then you say how and would choose which condition is evaluated first.
Note: "left to right" does apply in certain expressions like (a+b)*c
as you'd expect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With