SQLPathLab
Aggregation · Intermediate

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

Table:orders
orders
namedepartment
Alice Sales
Bob IT
Cindy Sales
David HR

Run result

result
departmentnames
HR David
IT Bob
Sales Alice,Cindy

Common issues

How do I guarantee order inside GROUP_CONCAT?

Write ORDER BY inside the function. A final query ORDER BY controls result rows, not value order within each concatenated group.

Why can the concatenated result be truncated?

MySQL limits it with group_concat_max_len. Check the production setting and avoid replacing proper detail rows with unbounded strings.

How does GROUP_CONCAT handle NULL?

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

Aggregation

Was this explanation clear?