How to display column values as CSV in MySQL?


To display column values as CSV, use GROUP_CONCAT().

Let us first create a table −

mysql> create table DemoTable786 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(100)
)  
AUTO_INCREMENT=101;
Query OK, 0 rows affected (0.70 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable786(StudentName) values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable786(StudentName) values('Robert');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable786(StudentName) values('Mike');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable786(StudentName) values('Sam');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable786;

This will produce the following output -

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 101       | Chris       |
| 102       | Robert      |
| 103       | Mike        |
| 104       | Sam         |
+-----------+-------------+
4 rows in set (0.00 sec)

Following is the query to select columns as CSV in MySQL −

mysql> select group_concat(StudentId),group_concat(StudentName) from DemoTable786;

This will produce the following output -

+-------------------------+---------------------------+
| group_concat(StudentId) | group_concat(StudentName) |
+-------------------------+---------------------------+
| 101,102,103,104         | Chris,Robert,Mike,Sam     |
+-------------------------+---------------------------+
1 row in set (0.00 sec)
raja
Published on 09-Sep-2019 12:03:31
Advertisements