5

I am working with postgresql and I have a table like this:

Group | Name
======================================
1     | Mary
2     | Barry,Ann,Peter
3     | Max,Chris
4     | Richard,Mary,Peter,Oliver

The table is an example, you can consider there will be more than 10,000 different names, the max number of names in one group is 4.

I want to sort the name within each group alphabetically so the result would be like this:

Group | Name
======================================
1     | Mary
2     | Ann,Barry,Peter
3     | Chris,Max
4     | Mary,Peter,Oliver,Richard

Thanks

3
  • 5
    Normalize your data so you're not storing multiple values in a single column, and you can do this with a simple ORDER BY. If you choose to store data in a comma-separated list, expect to have to work extra hard every time you want to use it. The proper way would be to have 2 Barry, 2 Ann, 2 Peter in three separate rows, which would make the query ORDER BY Group, Name. Commented Mar 1, 2017 at 3:29
  • 1
    What is the type of name, text or text[]? Commented Mar 1, 2017 at 3:36
  • @kennytm the type of name is text Commented Mar 1, 2017 at 3:39

1 Answer 1

1
SELECT t.Group, string_agg(n.names, ',' ORDER BY n.names) AS Name
FROM my_table t,
     regexp_split_to_table(t.Name, ',', 'g') n(names)
GROUP BY 1
ORDER BY 1;
Sign up to request clarification or add additional context in comments.

1 Comment

Its giving error ERROR: regexp_split does not support the global option SQL state: 22023

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.