Operator Precedence: Why Your WHERE Clause Might Surprise You

Operator Precedence: Why Your WHERE Clause Might Surprise You

Have you ever written a SQL query and been surprised by the results? If so, you’re not alone. One of the most common sources of confusion in SQL is operator precedence—the rules that determine how logical operators like AND and OR in your queries are evaluated.


A Quick History Lesson

Operator precedence has been part of SQL since its early ANSI standardization in the late 1980s, and Microsoft SQL Server (T-SQL) has followed these rules since its inception. The rules haven’t changed: AND is always evaluated before OR unless you use parentheses to override the default order.


A Simple Example

Let’s say you have this table:

Article content

Now, consider this query:

SELECT * 
FROM Actors  
WHERE 
   ActorID = 1 AND ActorName = 'Rod' 
OR 
   ActorID = 2 AND ActorName = 'Jane'  
        

What do you expect? Many people expect this to return all rows where either the ActorID is 1 or 2, and the name matches. That would be 3 rows. But in reality, it returns only 2 rows:

  • (1, Rod)
  • (2, Jane)


Why? Operator Precedence!

T-SQL evaluates AND before OR, so this is why only “Rod” and “Jane” are returned—not “Freddy.” The query is interpreted as:

WHERE 
   (ActorID = 1 AND ActorName = 'Rod') 
OR 
   (ActorID = 2 AND ActorName = 'Jane')          


Article content
Logical Flow

Best Practice: Use Parentheses for Clarity

Most developers avoid this pitfall by always using parentheses and not leaving it to the interpreter.

But here’s the catch: because we’re so used to using parentheses, many of us don’t actually know the underlying precedence rules! This can lead to mistakes when parentheses are omitted or when reading someone else’s code.

Tip: Always use parentheses to make your intent clear—even if you know the precedence rules. It makes your code easier to read and less error-prone.

Takeaway

Operator precedence in T-SQL is simple, but easy to overlook. If you’re ever in doubt, add parentheses. Your future self (and your teammates) will thank you!

Checkout this link to learn more: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/operator-precedence-transact-sql?view=sql-server-ver17

To view or add a comment, sign in

Others also viewed

Explore topics