1

I have a table of cart with 2 columns (user_num, data).

user_num will have the phone number of user and data will have an array of object like [{ "id": 1, "quantity": 1 }, { "id": 2, "quantity": 2 }, { "id": 3, "quantity": 3 }] here id is product id.

 user_num |                                         data
----------+--------------------------------------------------------------------------------------
        1 | [{ "id": 1, "quantity": 1 }, { "id": 2, "quantity": 2 }, { "id": 3, "quantity": 3 }]

I want to add more data of products in above array of objects in PostgreSQL.

Thanks!

2
  • Which kind type of column data? Is it JSON or JSONB? Commented Dec 15, 2021 at 6:25
  • @Pooya It's JSON Commented Dec 15, 2021 at 6:27

1 Answer 1

1

To add the value use the JSONB array append operator ||

Demo

update
  test
set
  data = data || '[{"id": 4, "quantity": 4}, {"id": 5, "quantity": 5}]'
where
  user_num = 1;
Sign up to request clarification or add additional context in comments.

2 Comments

two more questions, How will I delete an object where id is 4 and How will I edit quantity?
I hope this sample helps you. I append a sample for updating and deleting property in the array. dbfiddle.uk/…

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.