Combining multiple rows into a comma delimited list in MySQL?


To combine multiple rows into a comma delimited list, use the GROUP_CONCAT() method. Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(30),
   Marks int
   );
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name,Marks) values('John',67);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable(Name,Marks) values('Carol',69);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(Name,Marks) values('Sam',69);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name,Marks) values('David',78);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(Name,Marks) values('Chris',69);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name,Marks) values('Bob',67);
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+-------+-------+
| Id | Name  | Marks |
+----+-------+-------+
| 1  | John  | 67    |
| 2  | Carol | 69    |
| 3  | Sam   | 69    |
| 4  | David | 78    |
| 5  | Chris | 69    |
| 6  | Bob   | 67    |
+----+-------+-------+
6 rows in set (0.00 sec)

Following is the query to combine multiple rows into a comma delimited list in MySQL −

mysql> SELECT Marks, GROUP_CONCAT(Name ORDER BY Name ASC SEPARATOR ', ')
   from DemoTable GROUP BY Marks;

Output

+-------+-----------------------------------------------------+
| Marks | GROUP_CONCAT(Name ORDER BY Name ASC SEPARATOR ', ') |
+-------+-----------------------------------------------------+
| 67    | Bob, John                                           |
| 69    | Carol, Chris, Sam                                   |
| 78    | David                                               |
+-------+-----------------------------------------------------+
3 rows in set (0.00 sec)
raja
Published on 13-Jun-2019 12:18:01
Advertisements