VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
COUNT tells you how many rows are in a group. GROUP_CONCAT tells you what
they were, by joining their values into 1 string. It is the aggregate that
keeps the detail instead of reducing it to a number.
Open the client with mysql -u root -p sakila before you start.
How GROUP_CONCAT works
GROUPING_COLUMN with the column that defines the groups, TABLE_NAME
with the table, COLUMN_NAME with the column to join, and SEPARATOR_TEXT with
what goes between the values. Both ORDER BY and SEPARATOR are optional, and they
live inside the brackets rather than in the query around them.
Without SEPARATOR the values are joined with a comma and no space. Without
ORDER BY they arrive in no particular order.
Examples
1) Join the values in each group
NC-17 film runs 185 minutes and WHERE
removed its rows before the grouping. A group with no rows left does not
appear.
2) Drop the repeats
DISTINCT inside the brackets removes duplicate values within each group.
DISTINCT each string would hold 1 copy of the rate per film in the
group, between 178 and 223 of them, and the 2 longest would run into the limit
the next section is about. This is also the default separator: a comma and
nothing else.
The result is cut off at group_concat_max_len bytes
This is the trap. The server truncates aGROUP_CONCAT result that gets too
long, and it does not raise an error. The limit is a setting, so the number
below is this server’s rather than a property of MySQL, and it counts bytes
rather than characters.
SHOW WARNINGS says what
was lost: Warning 1260 Row 65 was cut by GROUP_CONCAT(). The string holds 64
whole titles out of 1,000 and then stops in the middle of the 65th.
Run SHOW WARNINGS yourself after a GROUP_CONCAT to see the same message.
SET SESSION group_concat_max_len = 100000; raises the limit for the rest of
your connection and reverts when you reconnect. Because the limit counts bytes,
text outside ASCII is cut sooner than the number suggests: a character can take
up to 4 bytes in utf8mb4.
Treat a result whose length equals group_concat_max_len exactly as truncated
until you have checked, and watch the warning count in the footer.
Summary
- Use
GROUP_CONCATto join the values in a group into 1 string. - Put
ORDER BY,SEPARATORandDISTINCTinside the brackets. - Expect a comma with no space when you name no separator.
- Expect truncation at
group_concat_max_lenbytes, with a warning rather than an error. - Suspect truncation whenever the length equals the limit exactly.
See also
- Aggregate functions — the aggregates that return a number
- GROUP BY — building the groups this joins
- MySQL string functions — reshaping the string afterwards
- MySQL GROUP BY performance — what building these strings costs at scale

