d
Amit DhamuSoftware Engineer
 

Using string_agg in PostgreSQL

1 minute read 00000 views

Take a fruits table like below.

idnamecreated_atupdated_at
1apple2021-07-01 10:43:132021-07-01 10:43:13
2orange2021-07-01 10:43:132021-07-01 10:43:13
3strawberry2021-07-01 10:43:132021-07-01 10:43:13

Say we wanted to retrieve a comma-separated list of the IDs, we can use the string_agg to achieve this.

SELECT string_agg(id::text, ',') AS ids FROM fruits

This would give you a result set like:

ids
1,2,3