20

In MySql's interpreter, it's very easy to dump a table to the screen along with its field names.

There seems to be no simple way to export a table to a tab-delimted or CSV outfile including its column headers.

I'm trying to do this using only SQL or the Linux command line, without writing a program in another language.

Thank you

7 Answers 7

21

Piping the query to the commandline client outputs a tab separated list with the column names as the first line

$ echo "select * from surveys limit 5" | mysql -uroot -pGandalf surveys
phone   param1  param2  param3  param4  p0      p1      p2      p3      audio4  code    time
XXXXXXXXX       2008-07-02      11:17:23        XXXXXXXX        SAT     -       -       -       -       -       ERROR   2008-07-02 12:18:32
XXXXXXXXX       2008-07-02      11:22:52        XXXXXXXX        SAT     -       -       -       -       -       COLGADO 2008-07-02 12:04:29
XXXXXXXXX       2008-07-02      11:41:29        XXXXXXXX        SAT     -       -       -       -       -       COLGADO 2008-07-02 12:07:22
XXXXXXXXX       2008-07-02      12:16:19        XXXXXXXX        SAT     1       1       1       9       XXXXXXXXX_4.wav     OK      2008-07-02 16:14:27
XXXXXXXXX       2008-07-02      08:21:25        XXXXXXXX        SAT     1       1       1       1       XXXXXXXXX_4.wav     OK      2008-07-02 12:29:40
4
  • 3
    It's a hack rather than mysql provided function. I guess it may not work for other OSes.
    – janetsmith
    Aug 3, 2011 at 1:02
  • 2
    It's not a hack, per se. It of course may not work on systems that do not provide both a sane command line interface and the mysql command line client.
    – Vinko Vrsalovic
    Aug 4, 2011 at 21:34
  • Will this properly quote (escape) column names and data?
    – LarsH
    Apr 17, 2015 at 18:04
  • I used in this way, thanks @VinkoVrsalovic echo "select user_pass from wp_users"| mysql -uroot -proot wp_database > passwordList.txt
    – aiffin
    Jan 22, 2018 at 11:07
9

This little script should do it:

-- 1. choose the table and the output file here / this should be the only input

select 'mytable' into @tableName;
select 'c://temp/test.csv' into @outputFile;

-- 2. get the column names in a format that will fit the query

select group_concat(concat("'",column_name, "'")) into @columnNames from information_schema.columns
where table_name=@tableName;

-- 3. build the query

SET @query = CONCAT(
"select * from
((SELECT ",@columnNames,")
UNION
(SELECT * FROM `",@tableName,"`)) as a
INTO OUTFILE '", @outputFile, "'");

-- 4. execute the query

PREPARE stmt FROM @query;
EXECUTE stmt;
3
  • 1
    Will the columns as ordered by "SELECT * ..." be in the same order as the columns as listed from the information_schema.columns query? Not trolling here - just curious... Oct 22, 2012 at 21:06
  • @cafe876: Thanks for this solution. I just wonder why the apostrophe ` is needed. If I remove the both apostrophes the query does not work. If I want to add a constraint (e.g.: SELECT 'x > 1' INTO @constr) at this line: (SELECT * FROM ",@tableName," WHERE ",@cosntr,)) as a" -> this does not work. Any idea?
    – giordano
    Sep 12, 2013 at 13:46
  • @giordano: If you want to get an answer, you'll probably need to better define "does not work"; e.g. what error message did you see? You may also need to ask a separate question. However the backtick allows you to use column names that contain unusual characters.
    – LarsH
    Apr 17, 2015 at 18:03
4

I achieved that in this way:

echo "select * from table"| mysql database -B -udbuser -puser_passwd | sed s/\\t/,/g > query_output.csv

The -B option of mysql separates the columns by tabs, which are converted into commas using sed. Note that the headers are generated too.

3
  • 2
    BTW, I had to replace \\t on OSX with Ctrl-V t. May 1, 2013 at 17:38
  • @thekingoftruth Thank you for that! Otherwise all the letter t's in the output are replaced by commas.
    – crlane
    Jun 27, 2013 at 15:00
  • Note that if any of your exported values contain commas, they will not be properly escaped or quoted.
    – LarsH
    Apr 17, 2015 at 18:09
1

You can do this with the mysqldump command. Have a look at the --tab and --xml options.

4
  • I tested this and it did not give satisfactory results. Namely "sudo mysqldump --user=root --pass=mypass -T /home/mydir mydb mytable" yields "mysqldump: Got error: 1: Can't create/write to file '/home/mydir/mytable.txt' (Errcode: 13) when executing 'SELECT INTO OUTFILE'" Apr 21, 2009 at 17:24
  • You should not need to use sudo for this. Just make sure you're running mysqldump from an account that has permission to write to the output folder, that seems to be what the error is. Apr 21, 2009 at 17:46
  • 1
    Ok, got this to work by creating a directory with 777 permissions. However, it did not output the column names, just the data. Apr 22, 2009 at 6:37
  • Make sure you check the top of the file, generally these tools dump the schema first then the data. If you want a tab delimited file with the columns in the header, you may have to use --xml and perform a 2nd conversion step. Apr 22, 2009 at 8:15
0

I have created a procedure to automate the exporting of the contents of a larger number of tables to .csv file by using SELECT ... INTO OUTFILE. Please refer to the following if you have need for something like this

http://lifeboysays.wordpress.com/2012/06/23/mysql-how-to-export-data-to-csv-with-column-headers/.

It uses the method described by cafe876, but will work for one or a whole series of tables, plus you can set the delimiter and quote character to be used.

2
  • Wasn't able to find the file afterward... haha. May 1, 2013 at 8:11
  • thekingoftruth: If you look at the script, you'll find that output defaults to "/tmp". The file will be there, but you can specify any location for example you want like this: CALL export_important_tables('"',',','/home/steviewonder/'); And if you downvoted because of this, please remove the downvote, will you?
    – Lifeboy
    Nov 26, 2018 at 9:05
0

I used the above command and modified according to my requirement.
I needed to get passwords column from the wordpress mysql database in a text file , to do that i used the following below command

echo "select user_pass from wp_users"| mysql -uroot -proot wp_database > passwordList.txt
0

Question is about how to export single table using only SQL or Bash, but in case if someone is interested in dumping whole database with column names, this is how it can be done with Powershell.

Start Powershell in empty directory of your choice and execute these commands one by one:

# Set these variables, they will be used in subsequent commands:
$mysqlUsername = 'root'
$mysqlPassword = 'qwerty'
$mysqlDatabase = 'dbname'

# Stop mysql server if it's already running:
'shutdown;' | mysql -u $mysqlUsername "-p$mysqlPassword"

# Start mysql server in new console window with read permissions: 
Start-Process mysqld --secure-file-priv=

# Dump all tables to current directory:
mysqldump -u $mysqlUsername "-p$mysqlPassword" $mysqlDatabase --tab=.

# Populate $files variable with created files:
$files = Get-Item *.txt

# Every file is named after a table it contains. So for each file we will query server for corresponding table, extract first line from the response and prepend this line to original file:
$files | % {
 $f = $_
 $sql = "select * from $($f.BaseName) limit 1;"
 $resp = $sql | mysql -u $mysqlUsername "-p$mysqlPassword" $mysqlDatabase
 (Get-Content -Raw $f) | % { $resp[0] + "`n" + $_ } | Set-Content -NoNewline $f
}

# Finally, shutdown the server:
'shutdown;' | mysql -u $mysqlUsername "-p$mysqlPassword"

Now current directory contains whole database in TSV with column names. But, if your database had empty tables, their column names haven't been extracted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.