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.

3 thoughts on “Selecting into a CSV file in MySQL

  1. Eric

    With sqlite you can create csv just by setting the mode.

    .mode csv
    select list,items from table where a

  2. thats pretty much why I have a blog. So I can write out things I’m doing knowing I’ll revisit them later. Can’t even remember how many times I’ve looked up my own socket or mail tutorials. lol

Comments are closed.