How to rename database in MySQL

Rumman Ansari   Software Engineer   2024-06-11 11:19:36   11 Share
Subject Syllabus DetailsSubject Details
☰ Table of Contents

Table of Content:


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:

  1. 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;
    
    
  2. 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 the mysql 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, and backup.sql with the desired name for your backup file.

  3. 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.

  4. 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.