'Why jsonb-functions does not work on update when column is null?

I have a table with a jsonb column, where the column default value is null. Now when I try to update this column with data first time using jsonb_set or jsonb_insert I get UPDATE 1 as a result but actually, the column stays null.

I made little test-case:

CREATE SCHEMA test;
CREATE TABLE test.books (  
  book_id serial NOT NULL,
  data jsonb
);

INSERT INTO test.books (data) VALUES (null);
INSERT INTO test.books (data) VALUES ('{}');

Now I update both new records:

UPDATE test.books SET data = jsonb_set( data, '{zzz}', 'true', true) WHERE book_id = 1;
UPDATE test.books SET data = jsonb_set( data, '{zzz}', 'true', true) WHERE book_id = 2;

And result:

# select * from test.books;
 book_id |                data                
---------+------------------------------------
       2 | {"zzz": true}
       1 | 
(2 rows)

Even when the update yielded the same result for both updates, the first row remained untouched.

I looked into documentation but found nothing about such behavior. Why it does not work this way?

I am using Postgres 9.6



Solution 1:[1]

What worked for me to set a native JSON value of null within a JSONB variable was the following:

IF condition = 1 THEN
    response = jsonb_set(
                    jsonb_in => response::jsonb,
                    path => ('{response, data, my_key')::text[],
                    replacement => 'null'::jsonb,
                    create_if_missing => true
                );
END IF;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pink_demon