Logical Operator Precedence

Accessing and Changing Relational Data

Accessing and Changing Relational Data

Logical Operator Precedence

When more than one logical operator is used in a statement, NOT is evaluated first, then AND, and finally OR. Arithmetic (and bitwise) operators are handled before logical operators.

In this example, the advance condition pertains to psychology books and not to business books because AND has precedence over OR:

SELECT title_id, type, advance
FROM pubs.dbo.titles
WHERE type = 'business' OR type = 'psychology'
  AND advance > $5500

You can change the meaning of the query by adding parentheses to force evaluation of the OR first. This query finds all business and psychology books that have advances over $5,500:

SELECT title_id, type, advance
FROM titles
WHERE (type = 'business' OR type = 'psychology')
   AND advance > $5500

The use of parentheses, even when not required, can improve the readability of queries and reduce the chance of making a subtle mistake because of operator precedence. There is no significant performance penalty in using parentheses. This example is more readable than the original example, although they are syntactically the same:

SELECT title_id, type, advance
FROM pubs.dbo.titles
WHERE type = 'business'
   OR (type = 'psychology' AND advance > $5500)

See Also

Operators

WHERE