GROUP_CONCAT
concatenating values within each group
Overview
GROUP_CONCAT joins non-NULL text values within each group and can apply DISTINCT, ORDER BY, and SEPARATOR inside the function. Concatenation order is not stable unless specified. Long output is also limited by MySQL group_concat_max_len, so it should not be treated as an unlimited interchange format.
Basic syntax
SELECT department, GROUP_CONCAT(name) AS names FROM orders GROUP BY department;
Examples
GROUP_CONCAT example
The example groups names by department. Production SQL should add ORDER BY inside GROUP_CONCAT when repeatable ordering matters.
Sample table
orders| name | department |
|---|---|
| Alice | Sales |
| Bob | IT |
| Cindy | Sales |
| David | HR |
Run result
| department | names |
|---|---|
| HR | David |
| IT | Bob |
| Sales | Alice,Cindy |
Common issues
Write ORDER BY inside the function. A final query ORDER BY controls result rows, not value order within each concatenated group.
MySQL limits it with group_concat_max_len. Check the production setting and avoid replacing proper detail rows with unbounded strings.
NULL inputs are normally skipped. If every value in a group is NULL, the result is NULL; use COALESCE only when the business meaning is clear.
Tags
Was this explanation clear?
Thanks. This feedback will inform the next content review.