How to collapse rows into a comma-delimited list with a single MySQL Query?


To collapse rows into a comma-delimited list, use GROUP_CONCAT(). Let us first create a table −

mysql> create table DemoTable
(
   Id int,
   Name varchar(40)
);
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'Chris Brown');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(101,'Adam Smith');
Query OK, 1 row affected (0.84 sec)
mysql> insert into DemoTable values(101,'John Doe');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(100,'David Miller');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(101,'Carol Taylor');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(103,'Bob Taylor');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+--------------+
| Id   | Name         |
+------+--------------+
|  100 | Chris Brown  |
|  101 | Adam Smith   |
|  101 | John Doe     |
|  100 | David Miller |
|  101 | Carol Taylor |
|  103 | Bob Taylor   |
+------+--------------+
6 rows in set (0.00 sec)

Following is the query to collapse rows into a comma-delimited list −

mysql> select Id,group_concat(Name) from DemoTable group by Id;

This will produce the following output −

+------+----------------------------------+
| Id   | group_concat(Name)               |
+------+----------------------------------+
|  100 | Chris Brown,David Miller         |
|  101 | Adam Smith,John Doe,Carol Taylor |
|  103 | Bob Taylor                       |
+------+----------------------------------+
3 rows in set (0.00 sec)

Updated on: 10-Oct-2019

417 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements