How do I import a .sql file via the command-line?

Joshua Rosato
Published: 6 February 2018Last updated: 24 October 2023
Share:

If you've set up SSH access for a package then you can use one of two methods to import a MySQL database via the CLI.

If needed, please see our guide on how to connect to your package via SSH.

 

MySQL CLI

To import a SQL file via the command line, you can use the mysql command. Here’s how.

mysql -h hostname -u username -p database_name < file.sql

Replace hostname with your database server name.

Replace username with your database username.

Replace database_name with the name of the database where you want to import the SQL file.

Replace file.sql with the path to the SQL file you want to import.

After entering the command, you'll be prompted to enter the password for the specified username.

Enter the correct password, and the import process will begin.

Make sure the SQL file contains valid SQL commands and is in the correct format for the database you're using.

If the import is successful, the data from the file will be imported into the specified database.

 

Compressed Files

If the database file is zipped then you’ll need to unzip it first.

For a .zip file you can use the unzip command:

unzip databasefile.sql.zip

For a .gz file you can use the gunzip command:

gunzip databasefile.sql.gz

From here you can proceed to import the unzipped file as normal.

If the database file is zipped then you’ll need to unzip it first.

 

WP CLI

To import a SQL file using the WP-CLI tool, you can follow these steps. WP-CLI is a command-line tool for managing WordPress installations, and it includes a command for importing databases.

1. Navigate to your WordPress installation:

SSH into your package and navigate to the root directory of your WordPress installation.

2. Backup your current database (optional but recommended):

It's a good practice to create a backup of your existing database before performing an import. You can use the following WP-CLI command to export your database:

wp db export

This command will create a SQL dump of your database in the WordPress installation folder. You can use it as a backup in case anything goes wrong.

3. Import the SQL file:

Use the wp db import command to import the SQL file. Here's the command:

wp db import file.sql

4. Verify the import:

After the import is complete, you can verify by checking your WordPress site to ensure that the data from the SQL file has been imported correctly.

That's it! You've successfully imported an SQL file into your WordPress database using WP-CLI.

This method is especially useful for migrating WordPress sites or importing data into a new WordPress installation.