Explain Codes LogoExplain Codes Logo

Error importing SQL dump into MySQL: Unknown database / Can't create database

sql
mysql-errors
importing-data
database-privileges
Anton ShumikhinbyAnton Shumikhin·Jan 27, 2025
TLDR

To quickly address the import error, you first need to ensure that the target database is in existence:

CREATE DATABASE IF NOT EXISTS `database_name`;

Then, import with the following command:

mysql -u username -p your_database < dump.sql

Remember to check if the dump contains contradictory CREATE DATABASE or USE statements. You might need to edit or remove these before the import.

Unexpected errors may stem from MySQL bugs 42996 and 40477. In such cases, manually creating the database before the import serves as a good workaround.
Sometimes, it's better to start from scratch. If you are setting a completely new environment, use DROP DATABASE IF EXISTS to make sure you're starting with a clean slate.

Connecting to a MySQL server? Don't forget to replace localhost with the accurate IP address or domain:

mysql -h server_ip_or_domain -u username -p your_database < dump.sql

Is the database already existing and causing errors? Use -o flag with your mysql import command and let the code take its course.

And before you proceed, always double-check if the user has sufficient privileges to create databases.

Take control!

Privileges checklist

Does your MySQL user have the necessary rights? Let's see:

SHOW GRANTS FOR 'username'@'localhost'; -- I have the GRANT, said every user ever!

Missing something? Use the GRANT statement:

GRANT ALL PRIVILEGES ON `database_name`.* TO 'username'@'localhost'; -- Now who's got the power!

Edit your way out

A text editor can be your lifesaver when trouble's brewing in the SQL dump. Spot the rogue lines causing the errors and neutralize - either edit or remove.

Force import

Fret not when errors appear during import. Remember, your code is stronger than any error:

mysql -u username -p database_name --force < dump.sql -- Beware, I've unleashed the force!

The --force (-f) flag makes the code unstoppable. It will continue importing the rest of the data, making sure those pesky errors don't leave you data-deficient.

What if?

Bruised but not broken

Some long-standing MySQL bugs such as 42996 and 40477 might boil your blood. But remember, patience is a programmer's best friend.

Keep up to date

Ensure that your MySQL server is in tune with the times. An outdated version is a breeding ground for errors and bugs.

Seek guidance

Facing a tough fix? Fret not. When the going gets tough, the tough get help. Whether it's MySQL's documentation or the community, better to ask a question than correct a mistake.