My users
table contains a metadata
column of type json
.
Now, I want to add new metadata to a user while preserving existing values.
So I'm using the ||
operator to merge 2 JSON objects:
UPDATE users
SET metadata = metadata::jsonb || '{"test": true}'::jsonb
WHERE id=...
RETURNING *;
Everything works fine when there are already some existing metadata.
However, when the previous value is NULL
then the update doesn't work. The metadata
after update is still NULL
.
How can I improve my query so that it sets the new JSON object when the previous value is NULL
or merges the previous and new values otherwise?