GROUP_CONCAT

Description

This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.

Syntax

  1. > GROUP_CONCAT(expr)

The full syntax is as follows:

  1. GROUP_CONCAT([DISTINCT] expr [,expr ...]
  2. [ORDER BY {unsigned_integer | col_name | expr}
  3. [ASC | DESC] [,col_name ...]]
  4. [SEPARATOR str_val])

Arguments

ArgumentsDescription
exprRequired. It specifies one or more columns or expressions to join.
DISTINCTOptional. To eliminate duplicate values.
ORDER BYOptional. To sort values in the result. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword.
SEPARATOROptional. The default separator between values in a group is comma (,).

Returned Value

The return value is a nonbinary or binary string, depending on whether the arguments are nonbinary or binary strings.

It returns NULL if there are no non-NULL values.

Examples

  1. create table t1(a int,b text,c text);
  2. insert into t1 values(1,"a","bc"),(2,"ab","c"),(3,"aa","bb"),(3,"aa","bb");
  3. mysql> select group_concat(distinct a,b,c separator '|') from t1;
  4. +-----------------------------------+
  5. | group_concat(distinct a, b, c, |) |
  6. +-----------------------------------+
  7. | 1abc|2abc|3aabb |
  8. +-----------------------------------+
  9. 1 row in set (0.01 sec)
  10. mysql> select group_concat(distinct b,c separator '|') from t1 group by a;
  11. +--------------------------------+
  12. | group_concat(distinct b, c, |) |
  13. +--------------------------------+
  14. | abc |
  15. | abc |
  16. | aabb |
  17. +--------------------------------+
  18. 3 rows in set (0.01 sec)
  19. mysql> select group_concat(distinct b,c separator '|') from t1;
  20. +--------------------------------+
  21. | group_concat(distinct b, c, |) |
  22. +--------------------------------+
  23. | abc|abc|aabb |
  24. +--------------------------------+
  25. 1 row in set (0.01 sec)