Using EXISTS with LOGICAL_OR in BigQuery

Photo by Tekton on Unsplash

Using EXISTS with LOGICAL_OR in BigQuery

Long time, no see! Here's a quick SQL exercise that illustrates some important modern concepts.

So, we're given a list of updates per each order, and at each point in time we have some flags. Our goal here is to check for each order if there was any point in time when any of the flags had the value of 1.

No alt text provided for this image

We solve this by:

➡️ UNNEST the ARRAY where the indicators are stored, doing so in an inline select. Yes, you can use WHERE to filter the output of FROM UNNEST().
➡️ leverage EXISTS to only check the existence of such an entry (we don't want to retrieve it), resulting in a TRUE/FALSE result
➡️ use LOGICAL_OR aggregation function, grouped by order_id, to check if there is at least one entry where the flag from the previous step was true for that grain.

Happy querying!

Found it useful? Subscribe to my Analytics newsletter at https://www.notjustsql.com .