LOGICAL_AND and LOGICAL_OR are highly useful non-standard SQL functions in BigQuery. These aggregation functions are versatile:
- LOGICAL_OR: Returns
TRUE
if at least one value in the grouping bucket isTRUE
. - LOGICAL_AND: Returns
TRUE
if all values in the grouping bucket areTRUE
.
Use cases:
- Pair with
NOT
when needed. - Compute results for a bucket using
GROUP BY
or a window function withOVER (PARTITION BY ...)
. - Filter output with
HAVING
when usingGROUP BY
, or withQUALIFY
when using window functions.
Example: To compute customer data:
- Check if all orders are paid.
- Identify any outstanding orders (not shipped).
- Determine if olives were ordered in the last 3 months.
Alternative:
- Achieve similar results using
MIN
andMAX
:MIN([TRUE,..., FALSE]) = FALSE
MAX([TRUE,..., FALSE]) = MAX
.