How to rename database in MySQL
In MySQL, you cannot directly rename a database using a single SQL statement like you can with tables. However, you can achieve the same effect by following these steps:
-
Create a New Database: First, create a new database with the desired name using the
CREATE DATABASE
statement. You can specify the desired character set and collation if needed.Replace
new_database_name
with the desired name for your database.CREATE DATABASE new_database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; -
Transfer Data: Next, transfer the data from the old database to the new one. You can do this by exporting the data from the old database and importing it into the new one. You can use the
mysqldump
command-line tool to export the data and themysql
command-line client to import it.mysqldump -u username -p old_database_name > backup.sql mysql -u username -p new_database_name < backup.sql Replace
username
with your MySQL username,old_database_name
with the name of your old database, andbackup.sql
with the desired name for your backup file. -
Drop Old Database: Once you've transferred the data, you can drop (delete) the old database using the
DROP DATABASE
statement.DROP DATABASE old_database_name; Replace
old_database_name
with the name of your old database. -
By following these steps, you effectively rename your database from the old name to the new one. However, make sure to take appropriate backups and ensure that there are no active connections or operations on the database during the renaming process to avoid data loss or corruption.