Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

simplifying postgres queries

Note: Asking to improve the working code.

My data column is as follows

{
   "color":"red",
   "toy":{
      "id":27,
      "name":"Truck",
      "price":12,
      "available":true
   },
   "quantity":"12"
}

In the above data, I want to set available to false and price to zero.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To do this I Am using the below code.

UPDATE toys 
SET data=JSONB_SET(data, '{toy,available}','false') 
WHERE data->'toy'->>'id'='27';

UPDATE toys 
SET data=JSONB_SET(data, '{toy,price}','0') 
WHERE data->'toy'->>'id'='27';

My question is it possible to update both values in a single query?

Thanks.

>Solution :

Sure:

UPDATE toys
SET data = jsonb_set(
              jsonb_set(data, '{toy,available}', 'false'),
              '{toy,price}',
              '0'
           )
WHERE data->'toy'->>'id'='27';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading