How to Import SQL File into MySQL
Restore a backup or move data safely by importing a SQL file into the correct MySQL database.
Before you start
Import into an existing database
If the target database already exists, the standard import command is straightforward.
mysql -u username -p database_name < backup.sql
It reads the SQL file and executes its statements inside the target database.
Create the database first if needed
If the database does not exist yet, create it before importing unless the SQL file already contains a database creation step.
CREATE DATABASE database_name;
Running the import before the database exists causes an avoidable failure.
Import after creating the database
Once the database exists, run the import command against that database.
mysql -u username -p database_name < backup.sql
Create the database first, then import. This is the most predictable workflow when restoring to a fresh environment.
Import and save an error log
If the file is large or the environment is unfamiliar, capturing errors can make troubleshooting much easier.
mysql -u username -p database_name < backup.sql 2> import_error.log
If the import fails, you have a file containing the error messages instead of relying only on terminal output.
Check whether the tables were restored
Do not stop at the import command. Verify that tables now exist in the target database.
SHOW TABLES;
You should see the tables that were supposed to be restored by the SQL file.
Check whether the data is there too
If the tables exist but you want to confirm the data imported correctly, run a quick row count on an important table.
SELECT COUNT(*) AS cnt
FROM table_name;
An import can appear to work while still leaving you with missing or partial data if errors occurred partway through.
Common failure situations
Create the target database first, or confirm whether the SQL file is supposed to create it for you.
The import may fail if the SQL file tries to create tables that are already present in the target database.
The MySQL account may not have the privileges needed to create tables, insert rows, or run the statements inside the file.
If the source and destination environments differ, text data or table definitions may create import warnings or failures.
Common mistakes
Double-check the target database name before pressing Enter.
If the target database already contains important data, back it up first.
Check tables and row counts instead of assuming the import finished perfectly.
If there are errors, read them immediately before doing more database work on top of a broken restore.