Combining ANY_VALUE with HAVING in BigQuery

Senior Data Engineer • Contractor / Freelancer • GCP & AWS Certified
Search for a command to run...

Senior Data Engineer • Contractor / Freelancer • GCP & AWS Certified
No comments yet. Be the first to comment.
Short, practical posts on SQL and BigQuery — from core language features to advanced query patterns. A reference for data practitioners at every level.
A reminder that you don't necessarily need Airflow / Composer to orchestrate data in and out of BigQuery. If your workflows are not that complex or numerous, take a look at Google Cloud Workflows. It's a serverless orchestration engine, with good i...
Here's a useful Dataform concept: pre_operations and post_operations. As the name implies, these represent a set of actions that run before and after the main operation (table, view, or SQL operations

BigQuery has always been a SQL engine for tabular data. Object tables add an interesting twist to that. Instead of rows containing values, an object table gives you one row per file — pointing at da

Query your data lake with warehouse-grade security and performance — without moving a single file.

Ever run a heavy BigQuery SQL query, processed gigabytes of data — and then accidentally closed the tab or forgot to save the results? 😬 Don't re-run it. Your results are still there. BigQuery automa

You can use query parameters in BigQuery hashtag#SQL (now in the console as well!) — but how are they different from variables, and when should you use each? Both parameters and variables act as place

Here's another rather rare instance where I've used ANY_VALUE in
BigQuery. It's basically an aggregation function like SUM or COUNT except it retrieves a arbitrary value from the grouping.
I've posted about ANY_VALUE before, but today's query was a bit different.
In the example below, my goal is to find orders that contain a single value, belonging to a particular list of values.
In other words, which order consisted of exactly one item, with that being grapes or oranges?
We aggregate using COUNT to count the number of order lines in an order and ANY_VALUE to pick a random value from the list of order lines.
We then filter the aggregate results using HAVING, keeping only order that have exactly one order line and that order line being a grape or orange.
With ANY_VALUE of a single value being always that value, we can filter the result sets to what we need. It's entirely true that the same can be said of MIN or MAX for instance, but I think it would have been a little less obvious of why it was chosen like that.
As almost always with SQL, there are of course plenty of other ways to achieve the same result.
Found it useful? Subscribe to my Analytics newsletter at notjustsql.com.