← Back to all articles Database and code

MySQL: group_concat Allows You to Easily Concatenate the Grouped Values of a Row

A practical look at one of MySQL's most useful aggregation functions — with syntax, examples, and real-world use cases.

Last week I stumbled over a really useful function in MySQL: group_concat allows you to concatenate the data of one column of multiple entries by grouping them by one field. You can choose the separator to use for the concatenation.

Syntax

The full syntax is as follows:

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

According to the MySQL documentation, the function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values. To eliminate duplicate values, use the DISTINCT clause. To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC keyword to the name of the column you are sorting by in the ORDER BY clause.

Practical Example

To make things clear, let's use a simple example. Say you have the following table representing the currently logged in users on a server:

CREATE TABLE `logged_in` (
  `server` varchar(255) DEFAULT NULL,
  `user` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1

There is one row for each user which is logged in on a specific server (e.g. marc is logged in on Server A). If you want the resultset to have a single entry for every server with a concatenated list of all the users logged in on that particular server, you can use group_concat and group the results by the name of the server:

SELECT server,
group_concat(user SEPARATOR ',') AS logged_in_users
FROM logged_in
GROUP BY server;

This produces a single row per server with all logged-in users concatenated.

Reference: MySQL Documentation — group_concat