May 16, 2007 3

Selecting into a CSV file in MySQL

By morgamic in Mozilla, Technology

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 Responses to “Selecting into a CSV file in MySQL”

  1. Eric says:

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

    .mode csv
    select list,items from table where a

  2. Jim Plush says:

    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

  3. Jeremy Orem says:

    Another options is just:

    mysqldump database –fields-terminated-by=’,’ –fields-optionally-enclosed-by=’”‘ -T /tmp