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?
Returns the type of the outermost JSON value as a text string. Possible types are object, array, string, number, boolean, and null.
postgres-json-schema allows validation of JSON schemas in PostgreSQL. It is implemented as a PL/pgSQL function and you can use it as a check constraint to validate the format of your JSON columns. postgres-json-schema supports the entire JSON schema draft v4 spec, except for remote (http) references.
ZSON is a PostgreSQL extension for transparent JSONB compression. Compression is based on a shared dictionary of strings most frequently used in specific JSONB documents (not only keys, but also values, array elements, etc). In some cases ZSON can save half of your disk space and give you about 10% more TPS.
The JSONB data type stores JSON (JavaScript Object Notation) data as a binary representation of the JSONB value, which eliminates whitespace, duplicate keys, and key ordering. JSONB supports GIN indexes.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With