Skip to content

Instantly share code, notes, and snippets.

@mogumogu2333
Last active September 8, 2016 18:42
Show Gist options
  • Save mogumogu2333/519805f63300ee7379fabe98c3040469 to your computer and use it in GitHub Desktop.
Save mogumogu2333/519805f63300ee7379fabe98c3040469 to your computer and use it in GitHub Desktop.
# How to export a mysql table into csv file with header
# the overall ideas in to attach the column names to the select * ....into outfile .. statement
# (select 'c1','c2','c3') union select c1,c2,c3 from tbl into outfile 'cc.csv'...
# 1st get the column names
select GROUP_CONCAT(CONCAT("'",COLUMN_NAME,"'"))
from INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'my_table'
AND TABLE_SCHEMA = 'my_schema'
order BY ORDINAL_POSITION
# copy the columns' name into the following statement
SELECT 'ColName1', 'ColName2', 'ColName3'
UNION ALL
select * into outfile '<file_name>'
fields terminated by ',' optionally enclosed by '"'
lines terminated by '\n'
from <table_name>;
@mogumogu2333
Copy link
Author

mogumogu2333 commented Sep 8, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment