logo
March 6, 2023

[TIL] A small Tip for Using MySQL and Zipping

A Quick Tip for Exporting MySQL Dumps as Compressed Files

Today, I want to share a helpful tip for working with MySQL and zip files.

As a software engineer, you have likely encountered scenarios where dealing with large amounts of data in MySQL databases involves the need to compress and decompress sensitive data using zip files. However, tables with a lot of data can quickly become huge and slow down database performance, especially when transferring data to or from the database.

Zip files come in handy for this task. They can significantly reduce the size of binary data like images or documents while preserving their original quality.

Here is a helpful trick for dealing with zipped data in MySQL:

  • To pipe a zip file containing a single SQL file into MySQL, use the -p flag with unzip command:
  • plain text
    unzip -p DUMP_FILE.sql.zip | mysql -u MYSQL_USER -p DB_NAME
  • To import a gzipped SQL file into MySQL:
  • plain text
    gunzip < my_database.sql.gz | mysql -u MYSQL_USER -p DB_NAME
  • To backup MySQL to a gzip archive:
  • plain text
    mysqldump -u MYSQL_USER -p DB_NAME | gzip -9 > my_database.sql.gz

    Note, ensure that the zip/gzip archive file contains only a single SQL file. Remember to replace DB_NAME with the name of your database on the MySQL server.

    By compressing MySQL dump files before exporting them, you can significantly reduce the time and resources required for the process. Gzip is a popular compression format that is easy to use and widely supported. Give it a try the next time you need to export a MySQL database dump.