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

Postgres: Duplicate row but update a field in json

I’m trying to duplicate all rows in my table that contain a signalVersion: prod but in the duplicated row I’d like to set signalVersion to 0. There are two keys in my table, signal_key and signal_value and both are json objects. signalVersion is a property of the object in column signal_key. Below is an example of signal_key:

{
  "signalType": "OCR_ITEM", 
  "signalVersion": "prod"
}

This is the code I’ve written so far but it’s failing. Does anyone know why my syntax is incorrect?

insert into signals (signal_key, signal_value)
select signal_key -> '{"signalVersion": "0"}', signal_value
from signals
where signal_key @> '{"signalVersion": "prod"}';

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

>Solution :

You’ll want to use the || operator to merge {"signalVersion": "0"} into the signal_key, not ->:

insert into signals (signal_key, signal_value)
select signal_key || '{"signalVersion": "0"}', signal_value
from signals
where signal_key @> '{"signalVersion": "prod"}';

Alternatively, you could use json_set:

insert into signals (signal_key, signal_value)
select json_set(signal_key, array['signalVersion'], 0), signal_value
from signals
where signal_key @> '{"signalVersion": "prod"}';
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