How can we export data to a CSV file along with columns heading as its first line?

MySQLMySQLi Database

For adding the column values we need to use UNION statement. It can be demonstrated with the help of the following example −

Example

In this example data from student_info will be exporting to CSV file. The CSV file will have the first line as the name of the columns.

mysql>(SELECT 'id', 'Name', 'Address', 'Subject')UNION(SELECT id, Name, Address, Subject From student_info INTO OUTFILE 'C:/mysql/bin/mysql-files/student_25.CSV'
FIELDS ENCLOSED BY '"' TERMINATED BY ';' ESCAPED BY '"' LINES TERMINATED BY '\r\n');
Query OK, 7 rows affected (0.04 sec)

After executing the above query MySQL creates Student_25.CSV file which have the following values −

id;    "Name";      "Address";      "Subject"
101;   "YashPal";   "Amritsar";     "History"
105;   "Gaurav";    "Chandigarh";   "Literature"
125;   "Raman";     "Shimla";       "Computers"
130;   "Ram";       "Jhansi";       "Computers"
132;   "Shyam";     "Chandigarh";   "Economics"
133;   "Mohan";     "Delhi";        "Computers"
raja
Published on 20-Feb-2018 09:46:25
Advertisements