Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert Jsonb simple array into column group by

I have a simple table with a Jsonb array of phone numbers:

CREATE TEMP TABLE IF NOT EXISTS user_info (
    id serial,
    phone_numbers jsonb
);
INSERT INTO user_info values (1, '["123456"]'),(2, '["564789"]'), (3, '["564747", "545884"]');

SQLFiddle: SQLFiddle Link

now, I want to group the array of numbers into columns.
something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

phone_numbers id
123456 1
564789 2
564747 3
545884 3

I have tried the below query but it is not working:

select s.phone_numbers
from (
        select id,phone_numbers from sales_order_details,
         lateral jsonb_array_elements(phone_numbers) e
     ) s
group by s.phone_numbers

>Solution :

No need to nest queries:

select pn.phone_number,
       ui.id
from user_info ui 
  cross join jsonb_array_elements_text(ui.phone_numbers) as pn(phone_number)
order by ui.id  

Online example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading