The GROUP_CONCAT()
function in MySQL is used to concatenate values from multiple rows into a single string within each group defined by the GROUP BY
clause. It is often used to create a comma-separated list or concatenate strings within each group.
The basic syntax of the GROUP_CONCAT()
function is as follows:
sql
GROUP_CONCAT([DISTINCT] expression [ORDER BY {column_name | expr | position} [ASC | DESC] [, ...] [SEPARATOR str_val]])
DISTINCT
: Optional keyword to remove duplicate values before concatenation.expression
: The column or expression whose values you want to concatenate.ORDER BY
: Optional clause to specify the order in which values are concatenated within each group.ASC | DESC
: Optional sorting order for the ORDER BY
clause.SEPARATOR
: Optional parameter to specify the separator between concatenated values. The default separator is a comma (,
).
Here's an example to illustrate the usage of GROUP_CONCAT()
:
sql
SELECT department, GROUP_CONCAT(employee_name ORDER BY hire_date DESC SEPARATOR ', ') AS employee_list
FROM employees
GROUP BY department;
In this example:
- The
employee_name
values within each department
group are concatenated into a single string. - The concatenation is ordered by
hire_date
in descending order (ORDER BY hire_date DESC
). - The values are separated by a comma and space (
SEPARATOR ', '
).
It's important to note that the GROUP_CONCAT()
function is commonly used with the GROUP BY
clause. If you use it without grouping, it will aggregate all rows into a single concatenated string.
sql
SELECT GROUP_CONCAT(employee_name ORDER BY hire_date DESC SEPARATOR ', ') AS all_employees
FROM employees;
In this case, it concatenates all employee_name
values into a single string for all rows in the employees
table.
Be cautious about the length limitations of the result string, as there is a system variable group_concat_max_len
that determines the maximum length of the result string produced by GROUP_CONCAT()
. If your concatenated string exceeds this limit, you may need to adjust the variable or consider other solutions.