How to output MySQL query results in CSV format and display it on the screen, not a file?


To get the output MySQL query result in CSV format, use concat(). The syntax is as follows −

mysql> select concat(StudentId,',',StudentName,',',StudentAge) as CSVFormat from CSVFormatOutputs;

To understand the above syntax, let us create a table. The query to create a table is as follows−

mysql> create table CSVFormatOutputs
   -> (
   -> StudentId int not null auto_increment,
   -> StudentName varchar(20),
   -> StudentAge int,
   -> PRIMARY KEY(StudentId)
   -> );
Query OK, 0 rows affected (1.15 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Mike',23);
Query OK, 1 row affected (0.26 sec)

mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('John',26);
Query OK, 1 row affected (0.19 sec)

mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Sam',19);
Query OK, 1 row affected (0.20 sec)

mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Carol',27);
Query OK, 1 row affected (0.59 sec)

mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Bob',24);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement. The query is as follows−

mysql> select *from CSVFormatOutputs;

The following is the output −

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|         1 | Mike        |         23 |
|         2 | John        |         26 |
|         3 | Sam         |         19 |
|         4 | Carol       |         27 |
|         5 | Bob         |         24 |
+-----------+-------------+------------+
5 rows in set (0.00 sec)

Here is the MySQL query to get the output in CSV (Comma Separated Value) format to the screen using contact() method−

mysql> select concat(StudentId,',',StudentName,',',StudentAge) as CSVFormat from CSVFormatOutputs;

The following is the output displaying the CSV format records−

+------------+
| CSVFormat  |
+------------+
| 1,Mike,23  |
| 2,John,26  |
| 3,Sam,19   |
| 4,Carol,27 |
| 5,Bob,24   |
+------------+
5 rows in set (0.00 sec)

Updated on: 30-Jul-2019

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements