0

I need to update a jsonb column which contains data {"X":true}. I need to append a complex object of the type {"obj":{"a":1,"b":2}} so the final value of row for that column {"x":true,"obj":{"a":1,"b":2}} . What will be the query to update this row .

postgres version 12

Update - The following query update tableName set columnName = (select '{"obj":{"a":1,"b":2}}'::jsonb || columnName::jsonb) where ... returns successfully when there is a value present , but when the column is null it still remains null after running the update query . I need to be able to add {"obj":{"a":1,"b":2}} even when the column is null .

1 Answer 1

1

You can use the concatenation operator:

'{"X":true}'::jsonb || '{"obj":{"a":1,"b":2}}'::jsonb

If you want to update an existing column, use coalesce() to deal with NULL values:

update the_table
  set the_column = coalesce(the_column, '{}')||'{"obj":{"a":1,"b":2}}'

Online example

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

2 Comments

The following query update tableName set columnName = (select '{"obj":{"a":1,"b":2}}'::jsonb || columnName::jsonb) where ... returns successfully when there is a value present , but when the column is null it still remains null after running the update query .
@divyamsingh13: use coalesce() - see my edit. The select is useless btw.

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.