Insert JSON string into Postgres and return field

Michiel Borkent picture Michiel Borkent · Oct 3, 2016 · Viewed 18.7k times · Source

I want to insert a JSON string into a Postgres table with a jsonb field and want the insert query to return a part of the JSON. For example, I want to return the id in the example below. What goes on the question marks?

insert into mytable (myjson)
values ('{"id":123}') returning ???

Answer

a_horse_with_no_name picture a_horse_with_no_name · Oct 3, 2016

Use the ->> operator to extract the value of the id attribute:

insert into mytable (myjson)
values ('{"id":123}') 
returning (myjson ->> 'id');