Course contentsShow
← Data Science
Lesson 870 of 2,14522. SQL FoundationsFree lesson

Operator Precedence and Parentheses

Understanding evaluation order of logical operators and using parentheses to control logic flow and avoid errors.

Operator Precedence and Parentheses

You'll learn how SQL evaluates complex logical conditions and how to use parentheses to ensure your filters work exactly as intended.

When you combine multiple logical operators (AND, OR, NOT) in a single WHERE clause, SQL follows a specific evaluation order—just like how multiplication happens before addition in math.

Understanding Operator Precedence

SQL evaluates logical operators in this order:

  1. NOT (highest priority)
  2. AND (middle priority)
  3. OR (lowest priority)

This matters because without parentheses, SQL might interpret your logic differently than you intended.

Consider filtering customers: "Show me customers in California OR Texas AND with purchases over $1000."

Without parentheses, SQL reads this as:

  • Customers in Texas with purchases over $1000, OR
  • All customers in California (regardless of purchase amount)

The AND binds tighter to Texas, not both states!

Using Parentheses to Control Logic

Parentheses let you override precedence and group conditions explicitly:

-- Without parentheses: AND evaluated first
WHERE state = 'CA' OR state = 'TX' AND purchase_amount > 1000

-- With parentheses: OR evaluated first (correct!)
WHERE (state = 'CA' OR state = 'TX') AND purchase_amount > 1000

Think of parentheses like wrapping related ideas in a box—SQL evaluates what's in the box first, then applies outside conditions.

Best Practice

Always use parentheses when mixing AND and OR, even if precedence would give the correct result. It makes your intent crystal clear to others (and your future self) and prevents subtle bugs.

Key Takeaway: SQL evaluates NOT before AND before OR, but parentheses let you control the order explicitly—use them liberally when combining logical operators to avoid confusing results.