BigQuery · Array function
BigQuery UNNEST
UNNEST turns an array into a table with one row per element. Use FROM t CROSS JOIN UNNEST(t.arr) to flatten an array column, LEFT JOIN UNNEST to keep rows whose array is empty or NULL, and WITH OFFSET to get each element's position.
UNNEST is an operator, not a scalar function: it goes in the FROM clause and returns a table with one row per array element. You can unnest a literal on its own (SELECT * FROM UNNEST(['a', 'b'])), but the everyday use is joining it to the table that holds the array. The join is correlated: FROM orders CROSS JOIN UNNEST(orders.items) AS item produces one row per item and repeats the order's other columns on each. A comma (FROM orders, UNNEST(orders.items) AS item) means the same as CROSS JOIN, and for an array column you can drop the keyword entirely (FROM orders, orders.items AS item).
A CROSS JOIN drops every row whose array is empty or NULL, because there is nothing to join it to. It is a frequent cause of rows silently missing from flattened reports. LEFT JOIN UNNEST(orders.items) AS item keeps those rows once, with item set to NULL, and needs no ON clause.
UNNEST does not promise to return elements in array order. Add WITH OFFSET AS pos to get each element's zero-based position, then order by it, filter on it, or use it to read a second array at the same position. For an array of structs, such as event_params in the GA4 export, each field is available as alias.field, and SELECT * returns one column per field.
Outside FROM, UNNEST appears in one more place: after IN. WHERE 'sale' IN UNNEST(tags) is BigQuery's array-contains test. Writing SELECT UNNEST(tags) as in PostgreSQL fails with Syntax error: Unexpected keyword UNNEST. Snowflake's LATERAL FLATTEN and Spark's explode map to CROSS JOIN UNNEST; their outer variants (OUTER => TRUE, explode_outer) map to LEFT JOIN UNNEST.
Syntax
FROM from_item CROSS JOIN UNNEST(array_expression) [[AS] alias] [WITH OFFSET [[AS] offset_alias]]
FROM from_item LEFT JOIN UNNEST(array_expression) [[AS] alias] [WITH OFFSET [[AS] offset_alias]]
SELECT ... FROM UNNEST(array_expression) [[AS] alias] [WITH OFFSET [[AS] offset_alias]]
search_value [NOT] IN UNNEST(array_expression)Arguments and return value
| Argument | Description |
|---|---|
array_expression | The array to expand: an array column or path (orders.items), an array literal, or any expression that returns an ARRAY, such as SPLIT(tag_list, ','), GENERATE_ARRAY(1, 10) or JSON_QUERY_ARRAY(payload, '$.items'). |
alias | Name of the element column. For an array of structs it names the whole struct, so fields are read as alias.field. Without an alias, the struct fields are available as columns of their own. |
WITH OFFSET | Adds an INT64 column with each element's zero-based position. It is named offset unless you give it an alias. |
Returns: A table with one row per array element, plus the offset column when WITH OFFSET is used. NULL and empty arrays produce zero rows; NULL elements produce rows that contain NULL.
Examples
Flatten an array column with CROSS JOIN UNNEST
Order 1003 has an empty array, so it disappears from the result.
WITH orders AS (
SELECT 1001 AS order_id, ['keyboard', 'mouse'] AS items UNION ALL
SELECT 1002, ['monitor'] UNION ALL
SELECT 1003, ARRAY<STRING>[]
)
SELECT order_id, item
FROM orders
CROSS JOIN UNNEST(orders.items) AS item
ORDER BY order_id, item;| order_id | item |
|---|---|
| 1001 | keyboard |
| 1001 | mouse |
| 1002 | monitor |
Keep empty and NULL arrays with LEFT JOIN UNNEST
The same orders plus one with a NULL array. LEFT JOIN keeps both orders that have nothing to unnest and sets item to NULL.
WITH orders AS (
SELECT 1001 AS order_id, ['keyboard', 'mouse'] AS items UNION ALL
SELECT 1002, ['monitor'] UNION ALL
SELECT 1003, ARRAY<STRING>[] UNION ALL
SELECT 1004, CAST(NULL AS ARRAY<STRING>)
)
SELECT order_id, item
FROM orders
LEFT JOIN UNNEST(orders.items) AS item
ORDER BY order_id, item;| order_id | item |
|---|---|
| 1001 | keyboard |
| 1001 | mouse |
| 1002 | monitor |
| 1003 | NULL |
| 1004 | NULL |
Keep element order with WITH OFFSET
The offset is zero-based, so add 1 for a step number.
WITH sessions AS (
SELECT 'sess_42' AS session_id,
['view_item', 'add_to_cart', 'begin_checkout', 'purchase'] AS steps
)
SELECT session_id, step, pos + 1 AS step_number
FROM sessions
CROSS JOIN UNNEST(sessions.steps) AS step WITH OFFSET AS pos
ORDER BY pos;| session_id | step | step_number |
|---|---|---|
| sess_42 | view_item | 1 |
| sess_42 | add_to_cart | 2 |
| sess_42 | begin_checkout | 3 |
| sess_42 | purchase | 4 |
Read GA4 event_params without multiplying rows
GA4 exports store event parameters as an array of key/value structs (the real schema also has float_value and double_value). A scalar subquery over UNNEST picks one key per column and keeps one row per event.
WITH events AS (
SELECT
'page_view' AS event_name,
ARRAY<STRUCT<key STRING, value STRUCT<string_value STRING, int_value INT64>>>[
('page_location', ('https://shop.example.com/cart', NULL)),
('ga_session_id', (NULL, 1732350000)),
('engagement_time_msec', (NULL, 5400))
] AS event_params
)
SELECT
event_name,
(SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'page_location') AS page_location,
(SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS ga_session_id
FROM events;| event_name | page_location | ga_session_id |
|---|---|---|
| page_view | https://shop.example.com/cart | 1732350000 |
Common mistakes
- Losing rows with CROSS JOIN UNNEST or a comma join. Parent rows whose array is empty or NULL vanish, so order counts and revenue drop without any error. Use
LEFT JOIN UNNEST(...)when every parent row must survive. - Unnesting two arrays of the same row in one FROM clause.
FROM t, UNNEST(t.sizes) AS s, UNNEST(t.colors) AS creturns every combination (3 sizes and 4 colors give 12 rows), not pairs. To pair elements by position, unnest one arrayWITH OFFSET AS posand read the other withcolors[SAFE_OFFSET(pos)]. - Summing parent columns after flattening. Once items are unnested,
SUM(order_total)counts each order once per item. Aggregate inside the array instead:(SELECT SUM(i.price) FROM UNNEST(items) AS i). - Expecting array order without WITH OFFSET. Rows from UNNEST have no guaranteed order; order by the offset when the sequence matters.
- Using a scalar subquery when a key can repeat inside one array.
(SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'x')fails with Scalar subquery produced more than one element as soon as one event has the key twice. AddLIMIT 1or wrap the value in an aggregate such asMAX(...).
Cost and performance
- On-demand queries bill only the nested fields you reference. Reading
keyandvalue.string_valuefrom GA4'sevent_paramsscans fewer bytes thanSELECT event_params, which reads every field in the record. A dry run shows the difference before you run anything. - Filtering on unnested elements does not reduce bytes scanned: BigQuery still reads the referenced array fields of every row it scans. Restrict the table first with a partition filter or, for GA4's daily
events_YYYYMMDDtables, a_TABLE_SUFFIXrange. - Flattening multiplies rows before any aggregation, and re-grouping them afterwards needs a shuffle. When you need one value per parent row, a subquery over the array (as in the GA4 example) keeps the row count unchanged and needs no GROUP BY.
FAQ
How do I check if an array contains a value in BigQuery?
Use value IN UNNEST(array), for example WHERE 'sale' IN UNNEST(tags). BigQuery has no ARRAY_CONTAINS function. For a condition on struct fields, use EXISTS(SELECT 1 FROM UNNEST(items) AS i WHERE i.price > 100).
What is the difference between CROSS JOIN UNNEST and LEFT JOIN UNNEST?
Both return one row per array element. CROSS JOIN, and the comma shorthand, drops rows whose array is empty or NULL; LEFT JOIN keeps each of them once, with NULL in the element column.
How do I unnest GA4 event_params in BigQuery?
Pull each parameter with a scalar subquery: (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'page_location') AS page_location. Read value.int_value for numeric keys such as ga_session_id, and limit the date range with _TABLE_SUFFIX when you query events_*.
How do I unnest two arrays in parallel?
Unnest one array WITH OFFSET AS pos and index the other with other_array[SAFE_OFFSET(pos)]. Unnesting both in the FROM clause returns a cross product instead. See OFFSET and SAFE_OFFSET.
Related
Errors you may hit
More array functions
All BigQuery array functions · All functions · BigQuery error messages
