How exactly does using OR in a MySQL statement differ with/without parentheses?
I have this query:
SELECT * FROM users WHERE `date_next_payment` <= '2011-02-02' AND `status` = 'active' OR `status` = 'past due'
Return all(because of-*) the datas of a row which has either of the below thingsa) Date next Payment less than equal to 2011-02-02 and status equal to active b) status equal to past due Which does not return the correct results. However, adding parentheses around the OR conditions makes it work like so:
SELECT * FROM users WHERE `date_next_payment` <= '2011-02-02' AND (`status` = 'active' OR `status` = 'past due')
Return all(because of-*) the datas of a row which has either of the below thingsa) Date next Payment less than equal to 2011-02-02 and status equal to active b) Date next Payment less than equal to 2011-02-02 and status equal to past due Why is it different? This is because OR has lower operator precedence than AND. Whenever the DB sees an expression like
A AND B OR C
the AND is evaluated first, i.e. it is equivalent to
(A AND B) OR C
So if you explicitly want
A AND (B OR C) instead, you must put in the parentheses.
The precedence of operators determines the order of evaluation of terms in an expression. To override this order and group terms explicitly, use parentheses. For example:
mysql> SELECT 1+2*3; -> 7 mysql> SELECT (1+2)*3; -> 9