1

This is my table on PostgreSQL with name contacts: enter image description here

  1. I want to edit mobile1 value with this sql query:

update contacts->info set mobile1 = JSON_SET(mobile1, "123456") where id=5

but that says :: ERROR: syntax error at or near "->"

  1. and when i want to delete or add a value with this sql query:

delete orders->info->mobile2 where id=5

syntax error at or near "orders"

  1. Or ADD

update orders->info set mobile3 = JSON_SET(mobile3, "123456") where id=5

syntax error at or near "->"

What's my syntax problem? and how can I do add, update and delete on my json datatype table on PostgreSQL

1
  • Unrelated but this would be much better and easier with a normalized data design. Commented Dec 14, 2021 at 7:37

2 Answers 2

1

According to Postgres document for insert, update, or delete you should use JSONB operation or function.

Demo

  1. Update scenario:
update contacts
set info = jsonb_set(info::jsonb, '{mobile,mobile1}', '"123456"')::json
where id = 5;
  1. Delete scenario:
update contacts
set info = (info::jsonb #- '{mobile,mobile2}')::json
where id = 5;
  1. Add scenario:
update contacts
set info = jsonb_set(info::jsonb, '{mobile,mobile3}', '"123456"')::json
where id = 5;
Sign up to request clarification or add additional context in comments.

2 Comments

thanks all of above worked, how can i add multiple mobile numbers on 1 query , add mobile4,mobile5,mobile6 ?
You can use dbfiddle.uk/… if needed add multiple keys
1

Solution for your question 1.

Updating the mobile1 json value in the info json field :

   update contacts 
      set info = jsonb_set(info :: jsonb, '{mobile,mobile1}', '123456', true) :: json
    where id=5

Solution for your question 2.

Removing the mobile2 key/value pair from the info json field :

   update contacts 
      set info = (info :: jsonb #- '{mobile,mobile2}') :: json
    where id=5

Deleting the entire row from the contacts table :

delete from contacts where id=5

You should read carefully the manual Chapter 6. Data Manipulation and 9.16. JSON Functions and Operators

2 Comments

thanks, your solution for question 1 this error appeard : ERROR: column "123456" does not exist for question 2 that worked@ and for question 3 how can I add another on my mobiles for example mobile3=987456 ?
Yes indeed I copied / pasted your piece of code with double quotes instead of simple quotes. I've updated my answer.

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.