0% found this document useful (0 votes)
63 views2 pages

How Exactly Does Using or in A Mysql Statement Differ With/Without Parentheses?

The document discusses how using parentheses changes the behavior of OR conditions in a MySQL WHERE clause. Without parentheses, AND conditions are evaluated before OR, but parentheses group OR conditions first. This leads to different rows being selected. By adding parentheses around OR conditions, the query returns rows that match either the AND condition or either of the OR conditions, in the intended way.

Uploaded by

Kool Prashant
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views2 pages

How Exactly Does Using or in A Mysql Statement Differ With/Without Parentheses?

The document discusses how using parentheses changes the behavior of OR conditions in a MySQL WHERE clause. Without parentheses, AND conditions are evaluated before OR, but parentheses group OR conditions first. This leads to different rows being selected. By adding parentheses around OR conditions, the query returns rows that match either the AND condition or either of the OR conditions, in the intended way.

Uploaded by

Kool Prashant
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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

You might also like