'Sorting Comma Separated Values in Redshift

I have a column/field in Redshift with comma separated values.

my_field
apple,banana,candy
candy,banana
banana,apple

And I want to turn these into

my_field_sorted
apple,banana,candy
banana,candy
apple,banana

Is there an easy way to do this with native SQL/Redshift syntax? Do I have to resort to UDFs?

I don't have any experience creating UDFs - does anyone have a similar UDFs that they can share?

Or can someone help turn this function into an UDF?

def sort_comma_sep_values(x):
  if type(x) is str:
    list_of_x = x.split(',')
    list_of_x = list(dict.fromkeys(list_of_x))
    list_of_x = sorted(list_of_x)
    output = ','.join(list_of_x)
    return output
  else:
    return None


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source