Home >Database >Mysql Tutorial >How can we export the data to a CSV file with the column headers as the first row?
In order to add column values, we need to use UNION statement. This can be demonstrated with the help of the following example -
Example
In this example, the data from student_info will be exported to a CSV file. The first row of the CSV file will be the column names.
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'); Query OK, 7 rows affected (0.04 sec)
After executing the above query, MySQL creates the Student_25.CSV file with 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"
The above is the detailed content of How can we export the data to a CSV file with the column headers as the first row?. For more information, please follow other related articles on the PHP Chinese website!