BigQuery Arrays & Structs

Accessing ARRAY elements in BigQuery

Constantin LunguUpdated 1 min read

Photo by JJ Ying on Unsplash

So here's 3 ways we can access elements in a BigQuery array.

- by index: array[index], starting at 0
- using OFFSET(index): array[OFFSET(index)], also starting at 0
- using ORDINAL(1-based index)), starting at 1

The above will return an "index out of range" error if they are out of bounds, so to get around that you can using SAFE_OFFSET and SAFE_ORDINAL.

If you'd like to see what position each elements resides at in the array, check WITH OFFSET.

WITH input_data AS (


  SELECT ['a','b','c','d','e'] AS letters
)

SELECT

  letters[ORDINAL(2)] AS second_with_ordinal, -- 1 based

  letters[1]  second_with_index, -- 0-based

  letters[OFFSET(1)] second_with_offest, --0-based

  letters[SAFE_OFFSET(5)]  AS sixth_with_safe_offset, -- 0-based, safe: returns NULL when out of bounds

  letters[SAFE_ORDINAL(6)] AS sixth_with_safe_ordinal -- 1-based, safe: returns NULL when out of bounds

FROM input_data

BigQuery results: second_with_ordinal, second_with_index and second_with_offest are all b; sixth_with_safe_offset and sixth_with_safe_ordinal are null.


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