Charis Soteriades
Charis Soteriades

Reputation: 15

Get an array element from an array in a json attribute of a jsonb column

I am using postgres database and I have an array inside a json attribute in a jsonb column and I need to get the first element of that array. The jsonb_column structure is like the below:

"IndustryCode": {
"Code": "111110",
"Keys": [
  "11",
  "111",
  "111110"
],}

So far I can get all the query elements by issuing the query below

select jsonb_array_elements(jsonb_column->'IndustryCode'->'Keys' ) from myindustry;

How can I query to get the first element?

Upvotes: 0

Views: 886

Answers (1)

user330315
user330315

Reputation:

If you just want the first element, there is no need to unnest the whole array. the -> operator also accepts an integer which specifies the array index.

select jsonb_column -> 'IndustryCode' -> 'Keys' ->> 0 
from myindustry;

Note I used ->> to return the value as text not as jsonb

Upvotes: 1

Related Questions