Export (0) Print
Expand All
6 out of 7 rated this helpful - Rate this topic

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 the following example, the color condition pertains to Product Model 21 and not to product model 20, because AND has precedence over OR.

USE AdventureWorks2008R2;
GO
SELECT ProductID, ProductModelID
FROM AdventureWorks2008R2.Production.Product
WHERE ProductModelID = 20 OR ProductModelID = 21
  AND Color = 'Red'

You can change the meaning of the query by adding parentheses to force evaluation of the OR first. The following query finds only products under models 20 and 21 that are red.

SELECT ProductID, ProductModelID
FROM AdventureWorks2008R2.Production.Product
WHERE (ProductModelID = 20 OR ProductModelID = 21)
  AND Color = 'Red'

Using parentheses, even when they are 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. The following example is more readable than the original example, although they are syntactically the same.

SELECT ProductID, ProductModelID
FROM AdventureWorks2008R2.Production.Product
WHERE ProductModelID = 20 OR (ProductModelID = 21
  AND Color = 'Red')
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.