Export Results From MySQL Query To CSV

To export the results of a MySQL query to a CSV file use the following command.

mysql --user=username --password -h localhost database -B < query.sql | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > query_export.csv

This assumes you have created a SQL query in a file called "query.sql".

See this link to explainshell.com output for more information about the different parts of this command.

You can also use an inline query with the -e flag.

mysql --user=username --password -h localhost database -B -e "SELECT * FROM users;" query.sql | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > query_export.csv

The regular expression in use here works in the following way.

s/'/\'/          Replace ' with \'
s/\t/\",\"/g     Replace all \t (tab) with ","
s/^/\"/          at the beginning of the line place a "
s/$/\"/          At the end of the line, place a "
s/\n//g          Replace all \n (newline) with nothing

Initial code taken from https://stackoverflow.com/a/5395421.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.