Skip to main content

Command Palette

Search for a command to run...

Why you should use parentheses with AND & OR in SQL

Updated
1 min read
Why you should use parentheses with AND & OR in SQL
C

Senior Data Engineer • Contractor / Freelancer • GCP & AWS Certified

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.

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


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

More from this blog

D

Datawise: A blog on SQL, BigQuery, Analytics, Python Tips and Tricks

204 posts

Data Engineer with a passion for transforming complex data landscapes into insightful stories. Here on my blog, I share insights, challenges, and the ever-evolving dance of technology and business.