Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a JSONB value to null

I'm trying to update a bunch of jsonb values to null. Here's an example of what i'm trying to do and i'm getting the error below.

How can I set first-name to null in this case?

UPDATE users
SET
    fields = fields || '{"first-name": NULL}'
WHERE user_id = 1;
ERROR:  invalid input syntax for type json
LINE 3:  fields = fields || '{"first-name": NULL}'
                                    ^
DETAIL:  Token "NULL" is invalid.
CONTEXT:  JSON data, line 1: {"first-name": NULL...
like image 430
Catfish Avatar asked Mar 04 '23 01:03

Catfish


2 Answers

Use jsonb_set:

UPDATE users
SET
    fields = jsonb_set(fields, '{first-name}', 'null')
WHERE user_id = 1;
like image 197
Laurenz Albe Avatar answered Mar 05 '23 16:03

Laurenz Albe


If you want the null value inside the JSONB, then it must be a JSON null value, not an SQL NULL value. JSON null must be spelled in lower case.

like image 45
jjanes Avatar answered Mar 05 '23 17:03

jjanes