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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With