1

I want to update a column of JSONB objects. So If I have this table

another table I want to delete value1 and value2 from the rows that have a as 1 then I thought this query would work

UPDATE
    test AS d 
SET
    b = b - s.b_value 
FROM
    (VALUES
        (1, 'value1'),
        (1, 'value2')
    )
    AS s(a, b_value) 
WHERE
    d.a = s.a

but it gives me this result where value1 was not eliminated. some table

Is there a simple way to fix it? I want to make a query to delete this sort of stuff but it would be a blessing if it can be done in only one query. I got the original idea from here and here you can test the SQL query

1
  • You are trying to update the same row twice in a single update. That leads to inconsistent results. Commented Aug 29, 2022 at 19:56

1 Answer 1

1

You can subtract a text[] array of keys from a jsonb value like so:

with s (a, b_value) as (
  values (1, 'value1'), (1, 'value2')
), dels as (
  select a, array_agg(b_value) as b_values
    from s
   group by a
)
update test
   set b = b - dels.b_values
  from dels
 where dels.a = test.a;

db<>fiddle here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.