Module 02 · lesson 8

Parentheses and condition precedence

The task: "electronics or clothing, but only cheaper than $100". Without parentheses the query unexpectedly returns the pricey "Galaxy" and "ProBook". Why?

Precedence: AND is stronger than OR

When a condition has both AND and OR, the DBMS evaluates AND first and only then OR (AND has higher precedence). This is often not what we mean:

-- NOT what you expect:
WHERE category = 'Home' OR category = 'Books' AND price < 50

reads as Home OR (Books AND price < 50) — that is, all of Home passes regardless of price (even Espresso at $129).

Parentheses set the order

Parentheses make your intent explicit:

WHERE (category = 'Home' OR category = 'Books') AND price < 50

Now the price condition applies to both categories.

Rule: mixing AND and OR — add parentheses, even if it seems obvious as is.

Без дужок → СКБД читає так:Without parentheses → the DBMS reads it as: Sin paréntesis → el SGBD lo lee así: category='Home' OR (category='Books' AND price<50) AND сильніший — групується сам; увесь Home проходить (навіть за $129).AND binds tighter — it groups alone; all Home rows pass (even at $129). AND liga más fuerte: agrupa solo; pasan todas las de Home (incluso a $129). З дужками → як ти хотів:With parentheses → what you intended: Con paréntesis → lo que querías: (category='Home' OR category='Books') AND price<50 умова ціни діє на обидві категорії — саме те, що треба.the price condition applies to both categories — exactly right. la condición de precio se aplica a las dos categorías: justo lo correcto.

Your turn

You need products from "Electronics" or "Clothing", and also cheaper than $100. Output name, category, price. Don't forget the parentheses!

Summary

  • AND is evaluated before OR.
  • Parentheses make your intent explicit and protect against mistakes.