Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Query to CSV [duplicate]

Tags:

sql

mysql

csv

Is there an easy way to run a MySQL query from the linux command line and output the results in csv format?

Here's what I'm doing now:

mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/        /,/g' | tee
list.csv select id, concat("\"",name,"\"") as name from students EOQ

It gets messy when there are a lot of columns that need to be surrounded by quotes, or if there are quotes in the results that need to be escaped.

like image 224
vinay Avatar asked Jan 14 '14 06:01

vinay


1 Answers

You can use "INTO OUTFILE"

I.e.

SELECT a,b,c FROM my_table INTO OUTFILE '/ca.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'; 

This will create a file "ca.csv" with a comma between each line. There are a few other options like escaping field values, but that should be enough to get you started.

The whole thing:

mysql -u uid -ppwd -D dbname -e "SELECT a,b,c FROM my_table INTO OUTFILE '/ca.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';"

EDIT :- A link for you to look at: SELECT INTO

To escape the fields, you would need to add FIELDS ESCAPED BY '"' - This would add double quotes

like image 104
Doug Avatar answered Sep 25 '22 03:09

Doug