Click to Rate and Give Feedback
MSDN
MSDN Library
SQL Server
SQL Server 2008 R2
Database Engine
Development
Query Fundamentals
Logical Operators
 Logical Operator Precedence
Community Content
In this section
Statistics Annotations (0)
Collapse All/Expand All Collapse All
Other versions are also available for the following:
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')
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker