I am using a JSONB column in a subquery where I need to return a single value. Each row of the JSONB column has the following form:
jsonb_column
------------
{
'data': [
{'type': 1, 'other':'stuff'}
{'other':'stuff'}
{'type': 1, 'other':'stuff'}
],
'other':'stuff'
}
I would like to return the first non-null value of jsonb_column -> data -> type, which would return 1 in this example.
I have tried unnesting the array elements:
SELECT jsonb_array_elements(jsonb_column -> 'data') ->> 'type'
This works, but it produces multiple type values. When I try to COALESCE to get a single value, I get an error:
SELECT COALESCE(jsonb_array_elements(jsonb_column -> 'data') ->> 'type')
ERROR: set-returning functions are not allowed in COALESCE
Hint: You might be able to move the set-returning function into a LATERAL FROM item.
I'm not sure how to implement this hint, or whether it is even useful in this case. Am I on the right track with unnesting the array elements, or is there a better way to get the first field value from an array of jsonb objects?