Stochastic Nonsense

Put something smart here.

Saving MySQL Query Results Into Csv

Say you have a mysql query such as

1
2
3
4
select start_date, count(*), sum(impressions) as impr, sum( revenue) as revenue
from adsense_analytics_days
group by start_date
order by start_date desc

and you want to save the results into a csv file. MySQL makes this relatively simple:

1
2
3
4
5
6
select start_date, count(*), sum(impressions) as impr, sum( revenue) as revenue
into outfile 'ttt.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n'
from adsense_analytics_days
group by start_date
order by start_date desc

There is one final hitch — for security reasons, mysqld normally is not allowed read / write access to your entire drive and is instead restricted to its own directory. So saving to ‘~/work/blah.csv’ will fail. The output, at least on MacOS, is located in /usr/local/mysql/data/[my database name]. Under linux, I’d look at the output of which mysql / which mysqld to guess the install directory.

NB: this is the most efficient method to get query results to a file if you have access to the server on which mysqld is running. If you only have remote access to mysql, you’ll have to use mysql to write query results directly to disk.