From: | "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com> |
---|---|
To: | r piper <asterisktheserver(at)gmail(dot)com> |
Cc: | "pgsql-novice(at)postgresql(dot)org" <pgsql-novice(at)postgresql(dot)org> |
Subject: | Re: |
Date: | 2017-04-12 15:02:00 |
Message-ID: | CAKFQuwZfDgVXWOfrOKgKLVjFQUwCPmfJUedsWsY-uTQ-onBOfA@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-novice |
On Wed, Apr 12, 2017 at 7:38 AM, r piper <asterisktheserver(at)gmail(dot)com>
wrote:
> What is the ideal way to update multiple fields within a jsonb column?
>
> For example, if I had the data set
>
> '
> {
> "field1": true,
> "field2": 2,
> "field3": "Something",
> }
> '
>
> How would I update "field2" and "field3". Most questions on StackOverflow
> seem to be suggesting either a nested jsonb_set call or using the
> concat operator. Neither one of these solutions seems to be as straight
> forward as one would expect for updating more than one field in a jsonb
> column.
>
The jsonb_set function is canonical the one that updates an input jsonb
value. However, it can only update a single element at a time. The
concatenation operator doesn't update fields by itself by jsonb has the
property of "last one stays" when faced with multiple instances of a given
key. Thus if your data is amenable to leveraging that behavior, which your
example data is, you can more compactly create the effects of an update by
constructing a "update jsonb" and concatenating it against the original.
SELECT ($${
"field1": true,
"field2": 2,
"field3": "Something"
}$$::jsonb || $${
"field2": 3,
"field3": "Something Else"
}$$::jsonb)::text
If you have a thought for what would be a straight-forward way to
multi-update it would be good to share. The json area is getting attention
right now so feature requests have a decent chance of being added.
David J.
From | Date | Subject | |
---|---|---|---|
Next Message | Neha Khatri | 2017-04-20 05:12:36 | pg_ctl command option anomalies |
Previous Message | r piper | 2017-04-12 14:38:43 |