Matthew
Matthew

Reputation: 7725

MySQL logical operators

Given the query 'SELECT foo FROM bar WHERE a = x AND b = y OR c = z', how does it parse this query?

(a = x AND b = y) OR c = z?
a = x AND (b = y OR c = z)?

That is a simple example, but what about if you're mixing and matching AND / OR with even more search terms?

Upvotes: 2

Views: 4921

Answers (4)

kiswa
kiswa

Reputation: 14987

As already answered, AND would have precedence and be parsed first.

I think the answer you're really looking for here is: don't write a query like SELECT foo FROM bar WHERE a = x AND b = y OR c = z.

If what you mean is SELECT foo FROM bar WHERE ((a = x AND b = y) OR c = z) or you meant to have SELECT foo FROM bar WHERE (a = x AND (b = y OR c = z)) then write it that way from the beginning.

It will save you having to figure it out when you look at the query again next week (or month, or year) and it will make things easier on future maintainers as well.

Upvotes: 3

Rezlaj
Rezlaj

Reputation: 244

from the MySQL manual section 11.2.1. Operator Precedence: http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html

AND has precedence over OR. (a = x AND b = y) OR c = z is the equivalent expression.

Upvotes: 0

MarkusQ
MarkusQ

Reputation: 21950

AND is higher precedence.

Upvotes: 1

brian-brazil
brian-brazil

Reputation: 34122

(a = x AND b = y) OR c = z

http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html

Upvotes: 5

Related Questions