How to import large SQL files into MySQL using the command line

Import large SQL databases into MySQL

As a rule, most WordPress sites have small databases, and by “small” I mean under 100 MB. But e-commerce stores and news portals can easily grow to several hundred megabytes. Trying to import a file that size through phpMyAdmin usually ends with an error: the upload size limit, the PHP execution time limit, or a timeout.

Problem: How to import large SQL files into MySQL.

Solution: Use the command line. It has no upload or execution time limits.

Import with the mysql client

mysql -h 127.0.0.1 -u username -p database_name < "/path/to/database (1).sql"

-p without a value makes the client ask for the password, so it doesn’t end up in your shell history. The database must already exist; create it first if needed:

mysql -u username -p -e "CREATE DATABASE database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"

NOTE: If the path or filename contains spaces, wrap it in quotes as shown above.

Import a compressed dump

Large dumps are often stored as .sql.gz. There is no need to unpack them to disk first:

gunzip < /path/to/database.sql.gz | mysql -u username -p database_name

Export a database with mysqldump

For exporting a database, use mysqldump:

mysqldump -h 127.0.0.1 -u username -p --single-transaction database_name > "/path/to/database (1).sql"

--single-transaction makes a consistent dump of InnoDB tables without locking them, so the site keeps working during the export.

If the import fails with ERROR 1118 (42000), see the next article.