2

If I put this data to jsonb field:

{'name': 'pratha', 'email': '[email protected]', 'sub': { 'id': 1 } }

I was able to select name with this query:

SELECT data_field->>'name' from users where ....

However, When they are in array, this query doesn't work:

[
   {'name': 'pratha', 'email': '[email protected]', 'sub': { 'id': 1 } },
   {'name': 'john', 'email': '[email protected]', 'sub': { 'id': 2 } }
]

How can I select each name in array?

See here: http://sqlfiddle.com/#!17/22166

1 Answer 1

4

Do a lateral cross join of jsonb_array_elements() to get the array's elements. Then you can extract the name from each element.

SELECT sr.*,
       jae.e->>'name'
       FROM survey_results sr
            CROSS JOIN LATERAL jsonb_array_elements(sr.data_field) jae (e);

SQL Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.