how do i get the return value in json after an insert in sql?

Don’t use json_agg using to_jsonb():

INSERT INTO games (player, score)
VALUES ('john', 42) 
returning to_jsonb(games);

If you are inserting multiple rows and one a single large JSON array, you need to wrap this into a CTE:

with new_games as (
  insert into games (player, score)
  values ('john', 42), ('peter', 50)
  returning *
select jsonb_agg(to_jsonb(ng))
from new_games ng;

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top