Explain Codes LogoExplain Codes Logo

Postgresql GROUP_CONCAT equivalent?

sql
string-agg
array-agg
mysql
Nikita BarsukovbyNikita Barsukov·Aug 16, 2024
TLDR

In PostgreSQL, replace GROUP_CONCAT from MySQL with string_agg to aggregate string values within a group:

SELECT group_column, string_agg(value_column, ', ') AS combined_values FROM table_name GROUP BY group_column;

This command aggregates value_column within each group_column using ', ' as a separator.

How to handle specific scenarios

When you need specific ordering

Put your order of values in the hands of string_agg and let it sort them out:

SELECT group_column, string_agg(value_column, ', ' ORDER BY ordering_column) AS combined_values FROM table_name GROUP BY group_column;

No more anarchy in your strings!

Handling number fields like a champ

You see a numeric field, I see a string waiting to be unleashed. Give your numerics a new life:

SELECT group_column, string_agg(value_column::text, ', ') AS combined_values FROM table_name GROUP BY group_column;

Who said numbers can't join the text party?

When string_agg just doesn't cut it

Flex your array muscles with array_agg and array_to_string:

SELECT group_column, array_to_string(array_agg(value_column ORDER BY ordering_column), ', ') AS combined_values FROM table_name GROUP BY group_column;

Arrays aren't just for counting anymore.

Transitioning from MySQL

MySQL refugee? No problem, we've got a warm spot for you right here. The new syntax is just as familiar as your old GROUP_CONCAT.

Strengthen your knowledge

CSV isn't just about commas

Handling CSV formats? Remember the golden rule: Commas are like cliffhangers, they always bring more. Handle them wisely.

Smarter casting

One cast to rule them all. Optimize your queries with array_agg and a single post-aggregation cast to text. Strings have never been this efficient.

Custom aggregate functions

Though the days of rolling your own aggregate function are mostly over, it's a worthy technique to remember just for those special occasions.