Mysql Query – Use brackets for multiple conditions!

Often you might be in situations where you want to query your mysql database with multiple AND and OR statements in the WHERE clause., which is why i use brackets to nest either OR and AND statments. Those conditions within the brackets will be executed first in the mysql query.

Lets say for example,

SELECT * from `pricelist` where cost > 10 and color=’red’ or weight > 100

The best way to write above query is

SELECT * from `pricelist` where cost > 10 and (color=’red’ or weight > 100)

Notice from above sql statement we have used 3 conditions in the WHERE clause. Notice that our main criteria is to pick up results having cost greater than $10. This is because the condition statement within brackets get precedence and executed first.

It is always

Note: Often NOT using brackets will lead to mystery results produced by mysql.