V
V
Valentine2018-02-12 19:05:19
PostgreSQL
Valentine, 2018-02-12 19:05:19

How to do an UPDATE in JSONB?

The crux of the matter is as follows.
There is a test table with id and json fields. The json field of type jsonb contains entries in the json format:
{
"a" : 5,
"b" : 5,
"c" : 5
}
I can select data with
SELECT json->'s' FROM test WHERE id = 5;
How can UPDATE json->'s' = 6; be done?
How can I add a new key-value pair json->'d' = 5 to this object?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-02-12
@valentinesowl

You will have to overwrite the value of the json field. To change "from" to 6:

UPDATE test
SET json = json || '{"c":6}'::jsonb
WHERE id = 5;

To add a new key:
UPDATE test
SET json = json || '{"d":5}'::jsonb
WHERE id = 5;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question