Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of condition execution in MySQL

Tags:

database

mysql

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?

like image 562
wyatt Avatar asked Nov 30 '11 14:11

wyatt


People also ask

What is the correct order of SQL query execution?

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.

Does order of conditions matter in SQL?

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.


1 Answers

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

like image 144
gbn Avatar answered Oct 08 '22 08:10

gbn