3

My purpose is to update a jsonb column using jsonb_set, which is currently null, with an object having more than one key-value pairs. The update command executes successfully but it is not updating anything, the column is still coming up empty. I am trying the following query.

UPDATE tab 
  set value = jsonb_set(value, '{}', '{"a" : 100, "b" : [100, 200]}'::jsonb) 
where id = 100;

Any solutions ?

1
  • if value is null initially then use like this coalesce(value,'[]'::jsonb). Commented Sep 19, 2023 at 15:18

1 Answer 1

5

From what I've understood, it appears you don't need jsonb_set for this case. Simply cast the string to jsonb for updating

UPDATE tab 
  set value = '{"a" : 100, "b" : [100, 200]}'::jsonb
where id = 100 
--and value is null; --additional check if you need.

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I know this way. But how to achieve the same if I want to do with jsonb_set only ? Or, what I'm asking is not possible at all ?
@ShaliniJ. : Most likely not possible and nothing that I know of using jsonb_set .jsonb_set works only on existing jsons, to set a particular value. You are actually adding a new json, so it should be either an insert or update.

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.