Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL - Move data from jsonb array to separate table

In my PostgreSQL database I have the following schema:

CREATE TABLE slides (
    id integer,
    question jsonb DEFAULT '{}'::jsonb
);

CREATE TABLE suggestions (
    id integer,
    slide_id integer,
    suggestion_text text
);


INSERT INTO slides (id, question)
  VALUES (1, '{"suggestions": ["Suggestion 1", "Suggestion 2"]}');

Now I want to move question->>'suggestions' to a suggestions table. So

SELECT * FROM suggestions; should return:

------------------------------------------------------------------
id     | suggestion_test   | slide_id
------------------------------------------------------------------
1      | Suggestion 1      | 1     
2      | Suggestion 2      | 1   

How can I do this in PostgreSQL? Here is DBfiddle that You can experiment with: https://www.db-fiddle.com/f/oEQf7ntttV5Wu9wyiXbEFk/0

like image 978
Mateusz Urbański Avatar asked May 06 '26 21:05

Mateusz Urbański


1 Answers

I think the column suggestions.id should be serial:

CREATE TABLE suggestions (
    id serial,
    slide_id integer,
    suggestion_text text
);

Use the function jsonb_array_elements_text().

insert into suggestions(slide_id, suggestion_text)
select 
    id as slide_id, 
    value as suggestion_text
from slides
cross join jsonb_array_elements_text(question->'suggestions');

DbFiddle.

like image 196
klin Avatar answered May 08 '26 12:05

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!