snippetMajor
how to update a property value of a jsonb field?
Viewed 0 times
fieldupdatevaluepropertyhowjsonb
Problem
I have a jsonb type named attr field that contains the following:
how to change is_default to false?
I try to run below, but no luck.
{
"pid": 1,
"name": "john",
"is_default": true
}
how to change is_default to false?
I try to run below, but no luck.
update attr set attr ->> 'is_default' = false where sales_type = 2Solution
There are two ways to accomplish this:
Simply concatenating the new key/value pair:
This works because when concatenating two
The other way is to use
If you're on version 14 (released September 2021) or greater, you can simplify this to:
Simply concatenating the new key/value pair:
update the_table
set attr = attr || '{"is_default": false}';This works because when concatenating two
jsonb values, existing keys will be overwritten.The other way is to use
jsonb_set() that updates a value at a location specified through a "path" (which is defined through the elements of an array)update the_table
set attr = jsonb_set(attr, array['is_default'], to_jsonb(false));If you're on version 14 (released September 2021) or greater, you can simplify this to:
update the_table
set attr['is_default'] = to_jsonb(false);Code Snippets
update the_table
set attr = attr || '{"is_default": false}';update the_table
set attr = jsonb_set(attr, array['is_default'], to_jsonb(false));update the_table
set attr['is_default'] = to_jsonb(false);Context
StackExchange Database Administrators Q#295298, answer score: 26
Revisions (0)
No revisions yet.