BigQuery Standard SQL: how to return the first value of array?
Asked Answered
G

2

13

Small working example

SELECT SPLIT("hello::hej::hallo::hoi", "::")

returns an array [hello, hej, hallo, hoi] where I want to select the first element i.e. hello. BG Standard provides no FIRST, instead FIRST_VALUE(..) OVER() which I cannot get working for this example above, so

How can I select the first value of array with BigQuery Standard SQL?

Garay answered 7/4, 2018 at 19:16 Comment(0)
A
37

I think the documentation in BigQuery is pretty good. You can read about arrays here.

You can use either OFFSET() or ORDINAL(). The method would be:

select array[offset(0)]

or

select array[ordinal(1)]
Appetizer answered 7/4, 2018 at 19:19 Comment(1)
@JervisChionh . . . The answer is not appropriate for a comment. It requires unnesting and recreating the array.Appetizer
S
7

If you have NULL values

  select array[safe_offset(0)]
Saidee answered 24/2, 2023 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.