PostgreSQL 9.5 - update doesn't work when merging NULL with JSON

房东的猫 提交于 2019-12-06 04:01:30

问题


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?


回答1:


add coalesce:

UPDATE users
SET metadata = coalesce(metadata::jsonb,'{}'::jsonb) || '{"test": true}'::jsonb
WHERE id=...
RETURNING *;

it works similar like with normal strings NULL || something is always NULL



来源:https://stackoverflow.com/questions/41284698/postgresql-9-5-update-doesnt-work-when-merging-null-with-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!