Why you should use parentheses with AND & OR in SQL

If you filter the data in SQL with WHERE using multiple logical conditions tied with AND & OR, PLEASE use the parentheses them accordingly.

Because if you don't, your fellow team members are going to have a harder time understanding your intent.

You might also get unintended results based on how they are resolved:

... operators with the same precedence are left associative. This means that those operators are grouped together starting from the left and moving right.

AND has a higher order of precedence than OR, therefore, in the example below:

is_paid AND is_shipped OR customer_is_on_contract AND is_first_time_buyer

is equivalent to

( is_paid AND is_shipped) OR (customer_is_on_contract AND is_first_time_buyer).

It should also be noted that for comparison operators parentheses are required in order to resolve ambiguity since they are not associative like NOT/AND/OR.

No alt text provided for this image

Found it useful? Subscribe to my Analytics newsletter at notjustsql.com.