Skip to content
Common mistakes/SQL: Why OR Without Parentheses Changes Your Filter
Common mistake

SQL: Why OR Without Parentheses Changes Your Filter

AND runs before 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

SQL evaluates AND before OR. A filter writtencategory_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.

Wrong: AND binds tighter than OR
select product_name, category_id, price
from products
where category_id = 1
   or category_id = 2
  and price > 30
order by product_name
Right: parentheses group the OR
select 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.

Right: use IN for one-column lists
select product_name, category_id, price
from products
where category_id in (1, 2)
  and price > 30
order by product_name
Debug habit

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