Tag Archives: exporting mysql results to csv

Export MySQL query results to CSV from CLI

This post is mostly for me to be able to quickly look up the way to export MySQL query results to CSV from command line 🙂

Assuming there’s a users table with name and email as the columns, and you can get all users using this command:

You can export this data from the command line to a csv file like below:

The command run above generates a “tab separated file” or “tsv”

In case you want an Excel compatible csv, run this command:

The above query will produce a file with rows like these:

Couple of nits:
1) MySQL should have write permissions to the directory in which you’re trying to write the file.
2) There shouldn’t already be a file with the same name – which is a bit of a bummer when you’re iterating over queries and are trying to create the right version of the file.