Partilhar via


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.

SELECT ProductID, ProductModelID
FROM AdventureWorks.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 AdventureWorks.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 AdventureWorks.Production.Product
WHERE ProductModelID = 20 OR (ProductModelID = 21
  AND Color = 'Red')

See Also

Other Resources

Operators (Transact-SQL)
WHERE (Transact-SQL)

Help and Information

Getting SQL Server 2005 Assistance