SQL GROUP_CONCAT Function Explained

The GROUP_CONCAT function is used to combine multiple rows of data into one string with a specified delimiter. Its syntax is as follows:

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

Description of parameters:

  1. DISTINCT: an optional feature that removes duplicates, the function only returns unique values when DISTINCT is specified.
  2. Field to be merged, could be a column name, constant, or expression.
  3. ORDER BY: Optional parameter indicating the sorting rule before merging the data.
  4. ASC | DESC: Optional selection indicating the order of sorting, with the default being in ascending order.
  5. SEPARATOR: Optional choice that represents the separator used in the merged string, defaulting to a comma.

Suppose there is a table called students, which includes the following data:

+----+-------+---------+
| id | name  | class   |
+----+-------+---------+
| 1  | Alice | Math    |
| 2  | Bob   | English |
| 3  | Alice | Science |
+----+-------+---------+

The GROUP_CONCAT function can be used to merge the classes of students with the same name into one string. For example:

SELECT name, GROUP_CONCAT(class) AS classes
FROM students
GROUP BY name;

After executing the above query statement, the following results will be obtained:

+-------+-----------------+
| name  | classes         |
+-------+-----------------+
| Alice | Math,Science    |
| Bob   | English         |
+-------+-----------------+

You can see that the classes of students with the same name have been combined into one string and separated by commas.

bannerAds