0

In my PostgreSQL database I have the following schema:

CREATE TABLE survey_results (
    id integer,
    data jsonb DEFAULT '{}'::jsonb
);

INSERT INTO survey_results (id, data)
    VALUES (1, '{"user": {}, "survey": {}}');

INSERT INTO survey_results (id, data)
    VALUES (2, '{"user": {}, "survey": {}}');

I want to update all records in survey_results table to have the following values in data column:

{"user":{"dob": '1995'},"survey":{"id": '1234'}}

How can I do that? I tried to do that with jsonb_set but I was not able to set all keys. Any ideas?

Here is sqlfiddle:

https://www.db-fiddle.com/f/i49SiaQn6qWcwiWDxVbHnn/8

2
  • this would be sooo easy with a properly normalized data model. Commented May 7, 2018 at 13:48
  • You're right... Commented May 7, 2018 at 13:49

1 Answer 1

1

I assume you oversimplified your question, because with your sample data you can achieve what you want by simply overwriting the value in the column:

update survey_results
  set data = '{"user": {"dob": 1995}, "survey": {"id": 1234}}'::jsonb

If you want to preserve potential other keys in the JSON document, and only update those two key, you need to nest the jsonb_set() calls for each key you want to change:

update survey_results
  set data = jsonb_set(jsonb_set(data, '{user}', '{"dob": 1995}', true), '{survey}', '{"id": 1234}', true);
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.