204

In short: Is there any way to sort the values in a GROUP_CONCAT statement?

Query:

GROUP_CONCAT((SELECT GROUP_CONCAT(parent.name SEPARATOR " » ") 
FROM test_competence AS node, test_competence AS parent 
WHERE node.lft BETWEEN parent.lft AND parent.rgt 
  AND node.id = l.competence 
  AND parent.id != 1 
ORDER BY parent.lft) SEPARATOR "<br />\n") AS competences

I get this row:

Crafts » Joinery

Administration » Organization

I want it like this:

Administration » Organization

Crafts » Joinery

1

2 Answers 2

447

Sure, see http://dev.mysql.com/doc/refman/...tions.html#function_group-concat:

SELECT student_name,
  GROUP_CONCAT(DISTINCT test_score ORDER BY test_score DESC SEPARATOR ' ')
  FROM student
  GROUP BY student_name;
6
  • Your code is heavily relied upon for your specific answer, and therefore should not be placed anywhere but your original post. If you put it here in this comment, many programmers here won't see it, and you won't get the best possible response :)
    – Sampson
    Commented Jun 15, 2009 at 10:38
  • Sad but true. :) Is that code enough or should I write the whole query?
    – Ivar
    Commented Jun 15, 2009 at 10:42
  • Did you try ASC instead of DESC?
    – Sampson
    Commented Jun 15, 2009 at 10:52
  • 18
    I didn't know you could order by within a group_concat until this exact moment. Solves a problem I was having. Thanks!
    – DiMono
    Commented Jul 28, 2016 at 21:34
  • 1
    oh my god not only does this solve my problem but it allows me to sort a group concat result set and use other functions to pop off the first or last element or whatever in a list based on the sort order...this is amazing.
    – geilt
    Commented May 6, 2022 at 17:04
32

Do you mean to order by?

SELECT _key,            
COUNT(*) as cnt,            
GROUP_CONCAT(_value ORDER BY _value SEPARATOR ', ') as value_list      
FROM group_concat_test      
GROUP BY _key      
ORDER BY _key;

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