Rename a MySQL database

Written in



Problem: You need to change the name of a mysql database without reloading it.

MySQL used to contain a "RENAME DATABASE" command but it would occasionally hose the database.

RENAME {DATABASE | SCHEMA} db_name TO new_db_name;

This statement was added in MySQL 5.1.7 but was found to be dangerous and was removed in MySQL 5.1.23. … Use of this statement could result in loss of database contents, which is why it was removed. Do not use RENAME DATABASE in earlier versions in which it is present.

So what should you do instead?

If all your tables are physically located on the same disk, you can use "create db" + "rename table" to move tables between databases without reloading them.

-- ensure the char set and collate match the existing database.
SHOW VARIABLES LIKE 'character_set_database';
SHOW VARIABLES LIKE 'collation_database';

CREATE DATABASE `database2` DEFAULT CHARACTER SET = `utf8` DEFAULT COLLATE = `utf8_general_ci`;
RENAME TABLE `database1`.`table1` TO `database2`.`table1`;
RENAME TABLE `database1`.`table2` TO `database2`.`table2`;
RENAME TABLE `database1`.`table3` TO `database2`.`table3`;

This answer is also posted on stackoverflow.



Verified by MonsterInsights