Menu Close

How to rename a database in MySQL?

Today we will talk how do you can easily rename a database in MySQL.
At the MySQL version 5.1.7 was added a command to do this job named RENAME DATABASE

RENAME {DATABASE | SCHEMA} db_name TO new_db_name;

But it was removed on the MySQL version 5.1.23 because maybe it would result in data lost’s.

Then, let’s see some ways in which we can do this:

1. Using the RENAME TABLE command

As long as two databases are on the same file system, you can use RENAME TABLE to move a table from one database to another:

RENAME TABLE current_db.tbl_name TO other_db.tbl_name;

RENAME TABLE Syntax na Documentacao do MySQL

mysql> show tables;
+---------------------+
| Tables_in_oldSchema |
+---------------------+
| tb1                 |
| tb10                |
| tb2                 |
| tb3                 |
| tb4                 |
| tb5                 |
| tb6                 |
| tb7                 |
| tb8                 |
| tb9                 |
+---------------------+
10 rows in set (0.00 sec)

Now, let’s do a query to get our ALTER TABLE command:

mysql> SELECT CONCAT('RENAME TABLE ', GROUP_CONCAT( table_schema,'.',table_name, ' TO ','new_schema.',table_name,' '),';') as stmt FROM information_schema.TABLES WHERE table_schema LIKE 'oldSchema' GROUP BY table_schema\G
*************************** 1. row ***************************
stmt: RENAME TABLE oldSchema.tb10 TO new_schema.tb10 ,oldSchema.tb1 TO new_schema.tb1 ,oldSchema.tb9 TO new_schema.tb9 ,oldSchema.tb8 TO new_schema.tb8 ,oldSchema.tb7 TO new_schema.tb7 ,oldSchema.tb6 TO new_schema.tb6 ,oldSchema.tb5 TO new_schema.tb5 ,oldSchema.tb4 TO new_schema.tb4 ,oldSchema.tb3 TO new_schema.tb3 ,oldSchema.tb2 TO new_schema.tb2 ;
1 row in set (0.01 sec)

UPDATE:
if the output of the above query isn’t complete, that is because GROUP_CONCAT() function limits the result length, to change it run the below query:

SET SESSION group_concat_max_len = 4294967295;

It’s this, now we just need to run the returned statement as a new query to move all tables from the oldSchema to new one, don’t forget, first you need to create your new database after this you can run the returned statement as a new query.

2. using mysqldump

mysqldump [OPTIONS] --database oldSchema > oldSchema.sql
mysql new_schema < oldSchema.sql

Good, it’s this for today. enjoy!!!

Liked? Help and Share!