Tuesday, April 7, 2015

Export SQL query result into CSV file (on MySQL)

Quite often we want to run an SQL script which can take a long time and analize the data retrieved. In order to do so we can run the SQL query and export the data gathered into a CSV file that can be analized later on. For this you can simple do the following as an example:

SELECT your_date, count(your_counting_field) FROM your_table WHERE your_condition_field=your_condition

INTO OUTFILE '/tmp/your_csv_file.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

The bolded part is the one that performs the export of the result. This can be customized depending on your needs but basically this is it.

NOTE: this example is orientated to be done on mysql command shell

References:

https://dev.mysql.com/doc/refman/5.6/en/select-into.html

No comments:

Post a Comment