1

I created a PostgreSQL (v10.0) table with a jsonb-array column as follows:

CREATE TABLE test (id INT, animals jsonb)

INSERT INTO test VALUES
   (1, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]'),
   (2, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]')

Then I want add new animals to the first row as follows:

UPDATE test
SET animals = animals || '["[hamsters, 7]", "[chicken, 2]"]'::jsonb
WHERE id = 1;

However, I want to append only those elements that are not yet in the array. In this case only [chicken, 2].

1 Answer 1

2

probably simplest would be:

t=# with c as (select distinct e,min(o) over (partition by e) o from test, jsonb_array_elements(animals || '["[hamsters, 7]", "[chicken, 2]"]'::jsonb) with ordinality t(e,o) where id =1)
, r as (select jsonb_agg(e order by o) z from c)
t-# update test set animals = z from r where id = 1;
UPDATE 1
t=# select * from test;
 id |                             animals
----+------------------------------------------------------------------
  2 | ["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]
  1 | ["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]", "[chicken, 2]"]
(2 rows)
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.