0

So this is my jsonb array of objects. Column is called bids in my db.

bids column

 [
      {
        "id": "1",
        "size": "5.5Y",
        "price": 180
      },
      {
        "id": "f0d1d36a-f6af-409e-968e-54c1dc104566",
        "size": "6.5Y",
        "price": 22
      }
    ]

I want to update price property by the ID of an element for ex. "f0d1d36a-f6af-409e-968e-54c1dc104566", so the price would change from 22 to 150 IN ROW WHICH CONTAINS ELEMENT WITH DESIRED ID IN THE COLUMN. How can I do that?

Perke
  • 7
  • 3

1 Answers1

0
create table json_update (id integer, json_fld jsonb);
insert into json_update values (1, '[
      {
        "id": "1",
        "size": "5.5Y",
        "price": 180
      },
      {
        "id": "f0d1d36a-f6af-409e-968e-54c1dc104566",
        "size": "6.5Y",
        "price": 22
      }
    ]'
)
;


UPDATE
    json_update
SET
    json_fld = jsonb_set(json_fld, ARRAY[(idx)::text, 'price'::text], '150'::jsonb)
FROM (
    SELECT
        (row_number() OVER (ORDER BY t.a ->> 'id') - 1) AS idx,
        t.a
    FROM (
        SELECT
            jsonb_array_elements(json_fld)
        FROM
            json_update) AS t (a)) AS i
WHERE
    i.a ->> 'id' = 'f0d1d36a-f6af-409e-968e-54c1dc104566';

select * from json_update ;
 id |                                                         json_fld                                                          
----+---------------------------------------------------------------------------------------------------------------------------
  1 | [{"id": "1", "size": "5.5Y", "price": 180}, {"id": "f0d1d36a-f6af-409e-968e-54c1dc104566", "size": "6.5Y", "price": 150}]


Adrian Klaver
  • 15,886
  • 2
  • 17
  • 28
  • Thank you! Can i somehow maintain the id 1 record without deleting it? So it would keep the rest of array as it was – Perke Jan 29 '23 at 18:12
  • Oops, that is not good. Let me see what I can do. – Adrian Klaver Jan 29 '23 at 18:15
  • See corrected answer. – Adrian Klaver Jan 29 '23 at 18:45
  • Does It work for you also if you add a few more rows? I tried executing it without adding another condition in the last WHERE and also with adding another condition but either of times it didnt update the row for me. – Perke Jan 29 '23 at 19:16
  • More rows(objects) in the `json` or in the table? Add to your question what you attempted and what failed. – Adrian Klaver Jan 29 '23 at 21:17
  • I added picture for reference for you, wanted to change only the object in desired row I bumped into something like this: update tbl set col = new_col_value from (select id as ref_id, ... as new_col_value from tbl) as tbl_new where tbl_new.ref_id = tbl.id. Thank you in advance – Perke Jan 31 '23 at 16:16
  • **Do not** use images copy and paste as text into the question. – Adrian Klaver Jan 31 '23 at 16:18