Get values from all rows and display it a single row separated by comma with MySQL


For this, use GROUP_CONCAT(). Do not use GROUP BY clause, since GROUP_CONTACT() is a better and quick solution.

Let us first create a table −

mysql> create table DemoTable1371
   -> (
   -> Id int,
   -> CountryName varchar(40)
   -> );
Query OK, 0 rows affected (0.89 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1371 values(100,'US');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1371 values(100,'UK');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1371 values(101,'AUS');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable1371 values(101,'Angola');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1371;

This will produce the following output −

+------+-------------+
| Id   | CountryName |
+------+-------------+
|  100 | US          |
|  100 | UK          |
|  101 | AUS         |
|  101 | Angola      |
+------+-------------+
4 rows in set (0.00 sec)

Here is the query to get values from all rows and display it a single row separated by comma −

mysql> select group_concat(CountryName separator ',') from DemoTable1371;

This will produce the following output −

+-----------------------------------------+
| group_concat(CountryName separator ',') |
+-----------------------------------------+
| US,UK,AUS,Angola                        |
+-----------------------------------------+
1 row in set (0.00 sec)

Updated on: 11-Nov-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements