Site icon Daniel J. Choi

How to export and compress a large MySQL database

I recently had to export a database with over 50MM rows, and while I love using PHPMyAdmin for most database operations, the tool’s export functionality tends to crap out on larger data sets.  This article outlines how to export a large MySQL database (with compression to save space!).

Using mysqldump

Enter mysqldump, a database backup program originally written by Igor Romanenko.  The program ships with most MySQL installations, and can be used via the following simple command, entered in your favorite CLI (e.g., Terminal on Mac).

[syntax type=”html|php|js|css”]> mysqldump -u [mysql_user] -p [db_name] | gzip > [destination]/[result_file].sql.gz[/syntax]

You will be prompted to enter the password associated with the mysql_user specified.  There will not be confirmation that the command executed successfully (except for finding the output file).

The mysqldump command will by default export a SQL file with statements for re-creating the database (tables, rows, and all).  Note that the following replacements must be made in the above command:

If you’re interested, here are some notes on how the command works:

As a side-note, use the -h flag to indicate an external database server.

Exporting to CSV

If you’d like to export the database table data to CSV, you can also do that via mysqldump, though it will take a bit of jiggering.  Take a look at the following line:

[syntax type=”html|php|js|css”]> mysqldump -u [mysql_user] -p -t -T[destination] [db_name] –fields-enclosed-by=\” –fields-terminated-by=,[/syntax]

Again, you’ll need to replace the following:

Some notes on this command:

This command will actually output a .txt file for each table, but you can simply change the extension to .csv and open the files in whatever spreadsheet program you prefer!

For MAMP users

If you’re using MAMP on Mac OS, you may get an error “mysqldump: command not found“.  This is because your system can’t find mysqldump.  The executable for MAMP’s installation of MySQL can be found at “/Applications/MAMP/Library/bin/mysqldump“, so simply replace the path in the above command like so:

[syntax type=”html|php|js|css”]> /Applications/MAMP/Library/bin/mysqldump -u [mysql_user] -p [db_name] | gzip > [destination]/[result_file].sql.gz[/syntax]

If you want to avoid typing the full path in the future, you can add an alias to your bash config file. (future quick hint coming soon).

Exit mobile version