Selecting into a CSV file in MySQL

Standard

Often times you’ll get requests for a CSV dump of something in your database. From the CLI, I often just run a SELECT statement by hand to see what it is that I want then I get stuck thinking, “now how do I get this to CSV again?”.

Selecting into a CSV outfile isn’t hard, and I’ve done it many times, but everytime I do it I have to look it up so I’ll just blog it here for next time.

SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM test_table;

When in doubt, blog it out.