Tuesday, June 3, 2008

Writing Query Results to a File in MySQL

Blogging this mostly for my own reference, but I had to write query results to a file in MySQL today and hadn't ever had to do that before. Luckily it's darn simple. The following will write out a CSV with field data enclosed with quotation marks (which is important if the data itself may contain a comma).

SELECT whatever FROM whereever
INTO OUTFILE '/path/to/file.csv'

You can then open that up in your favorite spreadsheet program quite easily.



That's awesome. I have never seen that before. Just one question - I assume the path there is relative to the machine housing the MySQL server, not the ColdFusion server (unless they are the same machine of course)?

@Ben--yes, the path there is a server path, and I assume it would be relative to the MySQL executable, or to be safe it's probably best to give it a full path (which is what the example really is since this is on a Unix server). Also I was running all this within MySQL directly so it didn't involve CF, but if you executed this from CF the path would still be on the database server, not the CF server if they're on different physical boxes.

Ok, very cool.

One more thing--the user MySQL is running as has to have write permissions on the directory to which you want to write the file. If you get an "errcode 13" that's a file permission error meaning that the user MySQL is running as (either "nobody" or "mysql" is pretty common on Unix) doesn't have permissions to the directory you're trying to write to.

That's cool. I checked out to see how to accomplish this is T-SQL for MSSQL, and it looks like you can do it in MSSQL as well, although it isn't nearly as clean as that MySQL syntax.

Matt, This is indeed very helpful. I'm wondering if there's a more direct way to create a table loaded with the results from the query? I've been scouring around the web for this, but haven't found anyone with this particular need - perhaps it's just me!

No comments: