Search code examples
postgresqlstring-aggregation

Postgres to fetch the list having comma separated values


I am working on Postgres SQL and having below join query, when I execute this query I get two or 3 records for each employee, because each employee has 3 different types of email address 1) Home Address 2) Office address 3) social address.

select * from root.employee c
full outer join root.employee_email ce
on c.employee_id = ce.employee_id
order by c.employee_id limit 1000 offset 0;

What I want is that employee_email.email column to give the comma separated value in the output, how can we do that ?

Note: I've almost 1 million records in DB and will use Spring Batch to migrate data from Postgres to MongoDB. The same I would need to do for Phone


Solution

  • Aggregate by employee and use string_agg:

    select
        c.employee_id,         -- or just c.* assuming employee_id is a PK
        string_agg(ce.email, ',') as emails
    from root.employee c
    full outer join root.employee_email ce
        on c.employee_id = ce.employee_id
    group by
        c.employee_id
    order by
        c.employee_id
    limit 1000
    offset 0;