Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting a MySQL table into a CSV file

I have a MySQL table which has to be taken out as a CSV file. The query I used is

SELECT "ID","NAME","SALARY","SAL1","SAL2","SAL3","SAL4","SAL5","SAL6","SAL7","SAL8","SAL9","SAL10","SAL11","SAL12","SAL13","SAL14","SAL15","SAL16","SAL17","SAL18","SAL19","SAL20","SAL21","SAL22","SAL23","SAL24","SAL25","SAL26" UNION ALL SELECT * FROM addstock25 INTO OUTFILE "E:\\JOSE DATA\\addstock7.csv" FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'; 

This query works, but what if I have 200 column names? Is there a way to do it without manually typing it?

like image 568
user3304713 Avatar asked Apr 01 '14 10:04

user3304713


People also ask

How do I export a table to CSV?

To proceed, follow the below-mentioned steps: Step 1: First of all, start SQL Server Management Studio and connect to the database. Step 2: Next, under Object Explorer search for the database you want to export data in CSV. Step 3: Right-click on the desired database >> go to Tasks >> Export Data.


2 Answers

This command almost gives you what you want, and it even works with a remote server. The only caveat is that it generates a TSV file (fields are separated by a tab).

mysql mydb -e "select * from mytable" -B > mytable.tsv  

But you could convert it to CSV using sed, as suggested in this answer:

mysql mydb -e "select * from mytable" -B | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > mytable.csv 
like image 177
Rems Avatar answered Sep 29 '22 12:09

Rems


I'm not seeing why you can't do

SELECT * FROM addstock25 INTO OUTFILE "E:\\JOSE DATA\\addstock7.csv" FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' 
like image 35
pacifist Avatar answered Sep 29 '22 12:09

pacifist