0

So I have a column within my database called divisions that lives on the company table. using a simple SELECT divisions FROM companies; I get the division rows of course

{"{\"id\": \"c88c8cf6-4b23-4575-a99f-1da966ad68a4-ceo\", \"title\": 
 \"CEO\", ... }"}

What I need to do is return just one field of each JSONB, title for example.

I have tried various methods to do this, the closest I can find seems to be

SELECT json_array_elements(divisions->>'title'::jsonb) FROM companies;

but this gives back the error

ERROR:  invalid input syntax for type json
LINE 1: SELECT json_array_elements(divisions->>'title'::jsonb) FROM ...
                                           ^
DETAIL:  Token "title" is invalid.

any idea?

2 Answers 2

1

You need to unnest the PostgreSQL array first:

SELECT d->>'title'
FROM companies AS c
   CROSS JOIN LATERAL unnest(c.divisions) AS d(d);
Sign up to request clarification or add additional context in comments.

1 Comment

This worked with a little bit of finageling, SELECT d ->> 'title' as title FROM companies AS c CROSS JOIN LATERAL unnest(c.divisions) AS d(d); got what I needed!
0

unnest() the array column using a CROSS JOIN, then you can use each jsonb document normally.

testdb=# create table companies(company_id integer, divisions jsonb[]);
CREATE TABLE
testdb=# insert into companies select 1, ARRAY['{"title": "Foo Co"}', '{"title": "Bar Inc"}']::jsonb[];
INSERT 0 1
testdb=# insert into companies select 2, ARRAY['{"title": "Baz Ltd"}']::jsonb[];
INSERT 0 1
testdb=# select company_id, div->>'title' as title
from companies
cross join unnest(divisions) as div;
 company_id |  title  
------------+---------
          1 | Foo Co
          1 | Bar Inc
          2 | Baz Ltd
(3 rows)

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.