Operator Precedence
Operator Precedence
Definition
Operator precedence determines which operators are evaluated FIRST when a SQL expression combines several without explicit parentheses — the same general concept as arithmetic's "multiplication before addition," applied to SQL's full operator set.
How It Works
A simplified precedence order (highest to lowest, roughly):
- Arithmetic (
*,/,%before+,-) - Comparison operators (
=,<,>,BETWEEN,IN,LIKE,IS NULL) NOTANDOR
sqlWHERE category = 'Books' OR category = 'Stationery' AND price < 100 -- evaluates as: WHERE category = 'Books' OR (category = 'Stationery' AND price < 100)
Because AND binds tighter than OR (12.5), this returns ALL Books (regardless of price) PLUS Stationery under 100 — likely NOT the intent if the goal was "cheap items in either category." The fix is explicit parentheses: WHERE (category = 'Books' OR category = 'Stationery') AND price < 100.
Edge Cases and Pitfalls
- This exact AND-before-OR precedence trap is one of the most common real-world sources of subtly wrong
WHEREclauses — code that "runs fine" and returns SOME plausible-looking rows, while actually answering a different question than intended. - Arithmetic precedence inside SQL expressions follows the same rules learned in basic mathematics (
*//before+/-) —price + tax * 0.1computestax * 0.1first, then addsprice. - The safest general practice, given how easy precedence mistakes are to introduce and how hard they can be to spot in review, is to use explicit parentheses around any compound condition mixing more than one kind of logical or arithmetic operator — even where the default precedence would technically already produce the intended result.
Key Takeaways
- SQL operators have a defined precedence order (roughly: arithmetic, then comparisons, then NOT, then AND, then OR).
- AND binds tighter than OR — a genuinely common, genuinely dangerous source of wrong query logic when parentheses are omitted.
- Default to explicit parentheses around any compound expression — the small verbosity cost is worth the clarity and safety.