Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 944
Flushed Avatar asked Dec 22 '16 13:12

Flushed


People also ask

Can JSON be null Postgres?

Returns the type of the outermost JSON value as a text string. Possible types are object, array, string, number, boolean, and null.

Does Postgres validate JSON?

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.

Does Postgres compress JSON?

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.

What is a Jsonb?

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.


1 Answers

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

like image 108
JosMac Avatar answered Sep 27 '22 16:09

JosMac