
MySQL GROUP_CONCAT()
The MySQL GROUP_CONCAT()
function is used to concatenate the values from multiple rows into a single string, grouped by a specified column. This is particularly useful when you want to aggregate data from multiple rows into a comma-separated list, for example, when you want to combine values for a particular group or category.
The basic syntax of the GROUP_CONCAT()
function is as follows:
GROUP_CONCAT(expression ORDER BY column SEPARATOR separator)
expression
: The column or expression whose values you want to concatenate.ORDER BY column
: Optional. Specifies the order in which the values should be concatenated within each group.separator
: Optional. Defines the delimiter used to separate the concatenated values. The default separator is a comma (,
).
Here’s an example of how to use the GROUP_CONCAT()
function to concatenate values:
Suppose you have a table named fruits
with columns category
and fruit_name
, and you want to concatenate the names of fruits in each category:
SELECT category, GROUP_CONCAT(fruit_name) AS concatenated_fruits
FROM fruits
GROUP BY category;
In this example, the GROUP_CONCAT()
function groups the fruits by their category
and concatenates the fruit_name
values within each group, separated by commas.
The result might look something like this:
category | concatenated_fruits
--------- | ----------------------
Citrus | Orange,Lemon,Lime
Berries | Strawberry,Blueberry,Raspberry
Tropical | Banana,Pineapple,Mango
You can customize the separator and order of values as needed. This function is handy for creating summary lists, generating CSV-like output, or aggregating data in various ways, especially when dealing with data that’s distributed across multiple rows.