Export MySQL query results to CSV from CLI

Please share if you found it helpful!

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.

Enjoyed reading this piece? Subscribe to my newsletter

Enjoyed reading this piece? Subscribe to my newsletter

Exclusive insights from an engineer turned product manager on his journey to entrepreneurship. Packed with insights and learnings from my personal journey. Learn something new every week.

Thanks for subscribing!

Leave a Reply

Your email address will not be published. Required fields are marked *