42

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.)

Manfred Moser
  • 29,539
  • 13
  • 92
  • 123
Mike Moyer
  • 431
  • 1
  • 4
  • 4

3 Answers3

50

Try using this in place of group_concat in Presto ::

select 
  a,
  array_join(array_agg(b), ',')
from table
group by a
Rahul Ahuja
  • 501
  • 4
  • 2
30

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

array_join(array_distinct(array_agg(...)), ', ')
Jacob Rose
  • 430
  • 4
  • 6
  • 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 – y2k-shubham Sep 18 '18 at 06:09
  • You can simplify this to `array_agg(distinct b)` and leave off the `array_distanct()` part – swdev Jan 26 '23 at 01:00
4

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
duber
  • 2,769
  • 4
  • 24
  • 32