0

Please, somebody explain me why queries:

WHERE property_id = 1 OR property_id = 2
    AND property_id = 3

and

WHERE (property_id = 1 OR property_id = 2)
    AND property_id = 3

given different results?

And how MySQL define order in WHERE clause?

Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91
  • possible duplicate of [Mysql or/and precedence?](http://stackoverflow.com/questions/12345569/mysql-or-and-precedence) – Carsten Jun 24 '14 at 09:59
  • 2
    http://en.wikipedia.org/wiki/Order_of_operations#Programming_languages logical operators precedence is not specific to SQL – regilero Jun 24 '14 at 10:00
  • Err, because they are different queries? – user207421 Jun 24 '14 at 10:01
  • 1
    @EJP the question is why they're two different queries. A lot of people would think these should produce the same results because they would be evaluated in order, not according to some precedence rules. – scragar Jun 24 '14 at 10:05

2 Answers2

3

Because of the precedence of the AND/OR logical operators

The first query is equivalent to

WHERE property_id = 1 OR (property_id = 2
    AND property_id = 3)

Because AND has higher precedence than OR operator

mavroprovato
  • 8,023
  • 5
  • 37
  • 52
2

Check Manual Here for Operator Precedence

In your first query where clause check this condition property_id = 2 AND property_id = 3 because of AND operator is more precedence then OR Operator.

In second query where clause check first this condtion (property_id = 1 OR property_id = 2) because bracket have more precedence then other compare operator.

Your first query equivalent to

WHERE property_id = 1 OR (property_id = 2
    AND property_id = 3)
Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
  • So if I don't use brackets, MySQL look up all AND operators and calc them, and then look up OR operators for calculation? – Victor Bocharsky Jun 24 '14 at 10:07
  • If don't use brackets then first evaluate `AND` operator after that evaluate `OR` operator because `AND` operator is more precedence than `OR` operator – Sadikhasan Jun 24 '14 at 10:10