1

I have an array of jsonb elements (jsonb[]), with id and text. To remove an element I could use:

UPDATE "Users" SET chats = array_remove(chats, '{"id": 2, "text": "my message"')

But I want to delete the message just by the id, cause getting the message will cost me another query.

  • Please provide a table definition and example values. I can derive that you are using Postgres 9.4, but that should be in your question, too. Do you want to remove the element from all rows like your example suggests or from just one row? Can there be various combinations of id and text? – Erwin Brandstetter May 3 '15 at 3:56
4

Assuming missing information:

  • Your table has a PK called user_id.
  • You want to remove all elements with id = 2 across the whole table.
  • You don't want to touch other rows.
  • id is unique within each array of chats.

UPDATE "Users" u
SET    chats = array_remove(u.chats, d.chat)
FROM  (
   SELECT user_id, chat
   FROM   "Users", unnest(chats) chat
   WHERE  chat->>'id' = '2'
   ) d
WHERE  d.user_id = u.user_id;

The following explanation matches the extent of provided information in the question:

  • Thanks actually that's exactly what I wanted – leonprou May 3 '15 at 8:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.