SQL: Why OR Without Parentheses Changes Your Filter
AND binds more tightly than OR. Add parentheses so the filter matches your intent.
The symptom
A query returns rows that should have been excluded. You meant "products over $30 in either of these categories," but cheap ones slip into the result.
Why it happens
AND has higher precedence than OR, the way
multiplication binds tighter than addition. A filter written
category_id = 1 or category_id = 2 and price > 30, like the
unparenthesized version below, therefore means "category 1 products, or
category 2 products over $30." The price filter does not apply to category
1.
This is a quiet logic bug: the query runs, the output looks plausible, and the mistake only shows up if you inspect the rows that slipped through.
The fix
Use parentheses to group the OR conditions, so the price filter applies to both categories instead of just the one it sits next to.
select product_name, category_id, price
from products
where category_id = 1
or category_id = 2
and price > 30
order by product_nameselect product_name, category_id, price
from products
where (category_id = 1 or category_id = 2)
and price > 30
order by product_name
Only one Garden Shop product in categories 1 and 2 costs more than $30, but
the unparenthesized filter returns five: every category 1 product, whatever
its price. When a column can match several values, an IN list
says the same thing as the parenthesized version with less punctuation to
get wrong.
select product_name, category_id, price
from products
where category_id in (1, 2)
and price > 30
order by product_name
When a WHERE clause mixes AND and OR, add
parentheses even if the database would interpret it correctly. Future you
should not have to remember precedence rules to read the filter.
Learn more
Related
Use WHERE to keep only matching rows.
Comparisons, AND/OR, IN, BETWEEN, and LIKE.
SELECT, WHERE, ORDER BY, and LIMIT at a glance.
Paste an error message and find the fix, from GROUP BY to constraint failures.
Combine filters without changing the intended logic.
Nested SELECTs, IN, EXISTS, and correlation.