How to display data from a MySQL column separated by comma?


You can use GROUP_CONCAT() function from MySQL to display result as a comma separated list. Let us first create a table −

mysql> create table DemoTable
   (
   Value int
   );
Query OK, 0 rows affected (0.26 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values(50);
Query OK, 1 row affected (0.07 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
| 10    |
| 20    |
| 30    |
| 40    |
| 50    |
+-------+
5 rows in set (0.00 sec)

Following is the query to display data from a column separated by comma.

mysql> SELECT GROUP_CONCAT(Value) FROM DemoTable;

This will produce the following output −

+---------------------+
| GROUP_CONCAT(Value) |
+---------------------+
| 10,20,30,40,50      |
+---------------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

475 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements