Skip to content
Advertisement

Postgresql – Return a column resulting from join as single json column

I have a many to many relationship between users and roles table (A typical usecase). They are related together using a user_role table. I execute the below query:

This results to

How do I aggregate the roles into one json or array column, such that it results to :

Advertisement

Answer

demo: db<>fiddle

  1. Create a json object with jsonb_build_object, Postgres JSON functions
  2. Aggregate the json objects with jsonb_agg, Postgres aggregate functions

Of course you can use type json instead of jsonb as well; Postgres JSON types

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement