BigQuery Arrays & Structs

The relationship between ARRAY_AGG and UNNEST

Constantin LunguUpdated 1 min read

Photo by Pawel Czerwinski on Unsplash

If you're working with nested data in BigQuery, you've might've seen UNNEST, which helps 'unpack' arrays into individual rows.

But there's also ARRAY_AGG, which, if you haven't encountered it before, which takes all rows for your GROUP BY bucket and creates an ARRAY out of them.

So, in essence, ARRAY_AGG and UNNEST are doing the exact opposite of each other.

Check my previous posts on the topic:

SELECT
  customer_id,
  ARRAY_AGG(STRUCT(order_id,
                   product)) AS orders
FROM unnested_data
GROUP BY customer_id

BigQuery results of the ARRAY_AGG query: one row per customer with a nested orders array, customer 1 with orders 101 apples and 102 tomatoes, customer 2 with 201 cherries and 202 cucumbers.

SELECT
  customer_id,
  _order.order_id,
  _order.product
FROM array_data
LEFT JOIN UNNEST(orders) AS _order

BigQuery results of the UNNEST query: the four flat rows again, customer 1 with 101 apples and 102 tomatoes, customer 2 with 201 cherries and 202 cucumbers.


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