Practical SQL

Why you should use parentheses with AND & OR in SQL

Constantin LunguUpdated 1 min read

Photo by Markus Spiske on Unsplash

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.

WITH input_data AS (
  SELECT 1 AS order_id, TRUE AS is_paid, FALSE AS is_shipped, TRUE AS customer_is_on_contract, TRUE AS is_first_time_buyer
  UNION ALL
  SELECT 2 AS order_id, FALSE AS is_paid, TRUE AS is_shipped, TRUE AS customer_is_on_contract, TRUE AS is_first_time_buyer
  UNION ALL
  SELECT 3 AS order_id, FALSE AS is_paid, FALSE AS is_shipped, TRUE AS customer_is_on_contract, FALSE AS is_first_time_buyer
)

SELECT *

FROM input_data

WHERE
      --is_paid AND is_shipped OR customer_is_on_contract AND is_first_time_buyer
      --resolved as:
     (is_paid AND is_shipped) OR (customer_is_on_contract AND is_first_time_buyer)

BigQuery results: orders 1 and 2 are returned; order 1 has is_paid true and is_shipped false, order 2 has is_paid false and is_shipped true, and both have customer_is_on_contract and is_first_time_buyer true.


Enjoyed this? Here are some related articles you might find useful: