SA0034 : Use parentheses to improve readability and avoid mistakes because of logical operator precedence

The topic describes the SA0034 analysis rule.

Message

Use parentheses to improve readability and avoid mistakes because of logical operator precedence

Description

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

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.

How to fix

Add parentheses around logical operator and its operands.

Scope

The rule has a Batch scope and is applied only on the SQL script.

Parameters

Rule has no parameters.

Remarks

The rule does not need Analysis Context or SQL Connection.

Effort To Fix
2 minutes per issue.
Categories

Design Rules, Code Smells

Additional Information

There is no additional info for this rule.

Example Test SQL
SQL
 1-- OR clause used without parenthesis
 2SELECT     title_id ,
 3           type ,
 4           price
 5FROM       pubs.dbo.titles
 6WHERE      type = 'physics'
 7        OR type = 'architecture'
 8       AND advance > 30
 9
10SELECT     title_id ,
11           type ,
12           price
13FROM       pubs.dbo.titles
14WHERE      type = 'physics'
15        OR ( type = 'architecture'
16             AND price > 30 )
17
18SELECT     title_id ,
19           type ,
20           price
21FROM       titles
22WHERE      ( type = 'physics'
23              OR type = 'architecture' )
24       AND advance > 30

Analysis Results
  Message Line Column
1 SA0034 : Use parentheses to improve readability and avoid mistakes because of logical operator precedence. 7 8
See Also

Other Resources