Tuesday, April 19, 2016

MySQL: How to export query results to a CSV file

You can use the following query, making sure you have write permission over the destination path.

SELECT field1, field2
FROM table_name INTO OUTFILE '/destination_path/result.csv' 
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

Including headers:

(SELECT 'label_field1','label_field2')
UNION 
(SELECT field1, field2
FROM table_name
INTO OUTFILE '/destination_path/result.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n');

No comments:

Post a Comment