Using ARRAY_AGG 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.
Everything you need to work effectively with nested and repeated data in BigQuery — ARRAY, STRUCT, UNNEST, ARRAY_AGG, and related functions.
title: "Using STRUCTS for Audit Fields in BigQuery" seoTitle: "BigQuery STRUCT Columns for Data Pipeline Audit Fields" seoDescription: "Shows how to use nested STRUCT columns in BigQuery to store audit metadata without cluttering your schema. Practic...
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

Almost everybody knows the usual standard SQL aggregation functions like SUM, MAX or AVG. In this short post, we're going to look at ARRAY_AGG: another useful aggregation function.
So, what does it do?
ARRAY_AGG allows us to aggregate multiple rows into a single array, based on a particular grouping. It's quite useful when modeling one-to-many relationships, like customers and orders.
For example, let's analyze the following input table.

Let's say we'd like to aggregate the order data into an ARRAY of STRUCTs, grouped by customer_id. Let's also order the resulting array decreasingly by the order_total .
The code to do that would look as follows:
SELECT
customer_id,
ARRAY_AGG( STRUCT(order_id, order_total ) ORDER BY order_total DESC) AS order_details
FROM input_data
GROUP BY customer_id
Here's how the processed data looks like:

We can now see that instead of the 6 initial rows, we have 2 rows - 1 per customer_id and an array of STRUCTS with order details.
Note that ARRAY_AGG can be combined with:
- DISTINCT, to eliminate duplicates in the resulting ARRAY
- STRUCT, to create an ARRAY of STRUCTS
- ORDER BY, to order the ARRAY in a particular way
- LIMIT, to keep only first n entries (based on the ordering)
Thanks for reading!
Found it useful? Subscribe to my Analytics newsletter at notjustsql.com.
Enjoyed this? Here are some related articles you might find useful: