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:

select 
    u.id, u.first_name, u.last_name, u.middle_name,
    u.email_address, r.id, r.role_code
from 
master.user u
left join
master.user_role ur 
    on ur.user_id = u.id
    and ur.is_void = false
left join
master.role r
    on r.id = ur.role_id
    and r.is_void = false
where u.id = 7  and u.is_void = false

This results to

7;"Multi Role";"First";"Middle";"mult@gmail.com";1;"ST"
7;"Multi Role";"First";"Middle";"mult@gmail.com";2;"TC"

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

7;"Multi Role";"First";"Middle";"mult@gmail.com";[{id: 1, role_code : ST}, {id: 2, role_code: TC}]

Advertisement

Answer

demo: db<>fiddle

SELECT 
    id, 
    first_name, 
    last_name, 
    middle_name, 
    email_address, 
    jsonb_agg(
        jsonb_build_object('id', r_id, 'role_code', role_code)
    )
FROM 
    result_table
GROUP BY id, first_name, last_name, middle_name, email_address
  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