Display MySQL Results as comma separated list?


We can show the result as a comma separated list with the help of the ‘concat()’ function with the parameter ‘,’.

Let us see an example now. Firstly, we will create a table. The CREATE command is used to create a table.

mysql> create table CommaSeperateDemo
   - > (
   - > Id int,
   - > FirstName varchar(100),
   - > LastName varchar(100)
   - > );
Query OK, 0 rows affected (0.93 sec)

Inserting records

mysql> insert into CommaSeperateDemo values(1,'John','Taylor');
Query OK, 1 row affected (0.17 sec)

mysql> insert into CommaSeperateDemo values(2,'Carol','Taylor');
Query OK, 1 row affected (0.12 sec)

mysql> insert into CommaSeperateDemo values(3,'Johnson','T.');
Query OK, 1 row affected (0.16 sec)

Let us now display all the records.

mysql> select *from CommaSeperateDemo;

The following is the output.

+------+-----------+----------+
| Id   | FirstName | LastName |
+------+-----------+----------+
|    1 | John      | Taylor   |
|    2 | Carol     | Taylor   |
|    3 | Johnson   | T.       |
+------+-----------+----------+
3 rows in set (0.00 sec)

Here is the syntax to get the result as comma separated list with the help of concat()

Select concat(ColumnName1, ',', ColumnName2, ',', ColumnName3,.............) as AliasName from yourTableName;

Let us now implement the above syntax in the following query.

mysql> SELECT concat(Id, ',', FirstName,',', LastName) as CONCATEIDFIRSTANDLASTNAME from CommaSeperateDemo;

The following is the syntax.

+---------------------------+
| CONCATEIDFIRSTANDLASTNAME |
+---------------------------+
| 1,John,Taylor             |
| 2,Carol,Taylor            |
| 3,Johnson,T.              |
+---------------------------+
3 rows in set (0.00 sec)

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements