48

I'm new to Presto and looking to get the same functionality as the group_concat function in MySQL. Are the following two equivalent? If not, any suggestions for how I can recreate the group_concat functionality in Presto?

MySQL:

select 
  a,
  group_concat(b separator ',')
from table
group by a

Presto:

select 
  a,
  array_join(array_agg(b), ',')
from table
group by a

(Found this as a suggested Presto workaround here when searching group_concat functionality.)

3 Answers 3

57

Try using this in place of group_concat in Presto ::

select 
  a,
  array_join(array_agg(b), ',')
from table
group by a
1
  • 3
    For those who see an unexpected order in the aggregation, you can use array_agg(x ORDER BY y)
    – spencer.sm
    Commented Dec 2, 2021 at 6:03
31

Also, if you're looking for unique values only – an equivalent to group_concat(distinct ... separator ', ') – try this:

array_join(array_distinct(array_agg(...)), ', ')
2
  • I've found that (in this particular case of achieving distinct group_concat) using nested queries for manually taking DISTINCT values performs better than the array_distinct UDF. Not sure that this would be universally true though Commented Sep 18, 2018 at 6:09
  • You can simplify this to array_agg(distinct b) and leave off the array_distanct() part
    – swdev
    Commented Jan 26, 2023 at 1:00
5

There's no function as of this answer, though the feature has been requested.

The closest equivalent is mentioned in your question.

WITH tmp AS (
SELECT 'hey' AS str1
UNION ALL
SELECT ' there'
)
SELECT array_join(array_agg(str1), ',', '') AS joined
FROM tmp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.