The MySQL manual at MySQL covers this.
Usually I just dump the database and reimport it with a new name. This is not an option for very big databases. Apparently RENAME {DATABASE | SCHEMA} db_name TO new_db_name;
does bad things, exists only in a handful of versions, and is a bad idea overall.
This needs to work with InnoDB, which stores things very differently than MyISAM.
For InnoDB, the following seems to work: create the new empty database, then rename each table in turn into the new database:
You will need to adjust the permissions after that.
For scripting in a shell, you can use either of the following:
OR
Notes:
-p
and the password. If your database has no password, remove the-u username -ppassword
part.If some table has a trigger, it cannot be moved to another database using above method (will result
Trigger in wrong schema
error). If that is the case, use a traditional way to clone a database and then drop the old one:mysqldump old_db | mysql new_db
If you have stored procedures, you can copy them afterwards:
mysqldump -R old_db | mysql new_db
Use these few simple commands:
Or to reduce I/O use the following as suggested by pablo720 Marin-Garcia:
I think the solution is simpler and was suggested by some developers. phpMyAdmin has an operation for this.
From phpMyAdmin, select the database you want to select. In the tabs there’s one called Operations, go to the rename section. That’s all.
It does, as many suggested, create a new database with the new name, dump all tables of the old database into the new database and drop the old database.
UPDATE 2022-09-22: MySQL 8.0+ added a more simpler solution:
Not sure since when has been added
RENAME TO
keywords, but sure is simpler. Though I would do a back up of the table before trying it, especially if you have a very large table. Anyway, it can be implemented as follow:I put it in two lines for easy reading but it can go in a single line as follow:
You can use SQL to generate an SQL script to transfer each table in your source database to the destination database.
You must create the destination database before running the script generated from the command.
You can use either of these two scripts (I originally suggested the former and someone “improved” my answer to use
GROUP_CONCAT
. Take your pick, but I prefer the original):or
($1 and $2 are source and target respectively)
This will generate a SQL command that you’ll have to then run.
Note that
GROUP_CONCAT
has a default length limit that may be exceeded for databases with a large number of tables. You can alter that limit by runningSET SESSION group_concat_max_len = 100000000;
(or some other large number).Emulating the missing
RENAME DATABASE
command in MySQL:Create a new database
Create the rename queries with:
Run that output
Delete old database
It was taken from Emulating The Missing RENAME DATABASE Command in MySQL.
You may use this shell script:
Reference: How to rename a MySQL database?
It’s working:
Three options:
Create the new database, bring down the server, move the files from one database folder to the other, and restart the server. Note that this will only work if ALL of your tables are MyISAM.
Create the new database, use CREATE TABLE … LIKE statements, and then use INSERT … SELECT * FROM statements.
Use mysqldump and reload with that file.
The simple way
Change to the database directory:
Shut down MySQL… This is important!
Okay, this way doesn’t work for InnoDB or BDB-Databases.
Rename database:
…or the table…
Restart MySQL
Done…
OK, this way doesn’t work with InnoDB or BDB databases. In this case you have to dump the database and re-import it.
Simplest bullet-and-fool-proof way of doing a complete rename (including dropping the old database at the end so it’s a rename rather than a copy):
Steps:
I’ve only recently came across a very nice way to do it, works with MyISAM and InnoDB and is very fast:
I don’t remember where I read it but credit goes to someone else not me.
Steps :
This is what I use:
MySQL does not support the renaming of a database through its command interface at the moment, but you can rename the database if you have access to the directory in which MySQL stores its databases. For default MySQL installations this is usually in the Data directory under the directory where MySQL was installed. Locate the name of the database you want to rename under the Data directory and rename it. Renaming the directory could cause some permissions issues though. Be aware.
Note: You must stop MySQL before you can rename the database
I would recommend creating a new database (using the name you want) and export/import the data you need from the old to the new. Pretty simple.
Well there are 2 methods:
Method 1: A well-known method for renaming database schema is by dumping the schema using Mysqldump and restoring it in another schema, and then dropping the old schema (if needed).
From Shell
Although the above method is easy, it is time and space consuming. What if the schema is more than a 100GB? There are methods where you can pipe the above commands together to save on space, however it will not save time.
To remedy such situations, there is another quick method to rename schemas, however, some care must be taken while doing it.
Method 2: MySQL has a very good feature for renaming tables that even works across different schemas. This rename operation is atomic and no one else can access the table while its being renamed. This takes a short time to complete since changing a table’s name or its schema is only a metadata change. Here is procedural approach at doing the rename:
Create the new database schema with the desired name.
Rename the tables from old schema to new schema, using MySQL’s “RENAME TABLE” command.
Drop the old database schema.
If there are views, triggers, functions, stored procedures in the schema, those will need to be recreated too
. MySQL’s “RENAME TABLE” fails if there are triggers exists on the tables. To remedy this we can do the following things :1)
Dump the triggers, events and stored routines in a separate file.
This done using -E, -R flags (in addition to -t -d which dumps the triggers) to the mysqldump command. Once triggers are dumped, we will need to drop them from the schema, for RENAME TABLE command to work.2) Generate a list of only “BASE” tables. These can be found using a query on
information_schema.TABLES
table.3) Dump the views in an out file. Views can be found using a query on the same
information_schema.TABLES
table.4) Drop the triggers on the current tables in the old_schema.
5) Restore the above dump files once all the “Base” tables found in step #2 are renamed.
Intricacies with above methods : We may need to update the GRANTS for users such that they match the correct schema_name. These could fixed with a simple UPDATE on mysql.columns_priv, mysql.procs_priv, mysql.tables_priv, mysql.db tables updating the old_schema name to new_schema and calling “Flush privileges;”. Although “method 2″ seems a bit more complicated than the “method 1″, this is totally scriptable. A simple bash script to carry out the above steps in proper sequence, can help you save space and time while renaming database schemas next time.
The Percona Remote DBA team have written a script called “rename_db” that works in the following way :
To demonstrate the use of this script, used a sample schema “emp”, created test triggers, stored routines on that schema. Will try to rename the database schema using the script, which takes some seconds to complete as opposed to time consuming dump/restore method.
As you can see in the above output the database schema “emp” was renamed to “emp_test” in less than a second. Lastly, This is the script from Percona that is used above for “method 2″.
When you rename a database in PHPMyAdmin it creates a dump, then drops and recreates the database with the new name.
For those who are Mac users, Sequel Pro has a Rename Database option in the Database menu.
http://www.sequelpro.com/
Most of the answers here are wrong for one of two reasons:
Percona has a blog post about how to do this well:
https://www.percona.com/blog/2013/12/24/renaming-database-schema-mysql/
and script posted (made?) by Simon R Jones that does what is suggested in that post. I fixed a bug I found in the script. You can see it here:
https://gist.github.com/ryantm/76944318b0473ff25993ef2a7186213d
Here is a copy of it:
Save it to a file called
rename_db
and make the script executable withchmod +x rename_db
then use it like./rename_db localhost old_db new_db
Seems noone mentioned this but here is another way:
then for each table do:
then, if you want to,
This approach would have the advantage of doing the entire transfer on server with near zero network traffic, so it will go a lot faster than a dump/restore.
If you do have stored procedures/views/etc you might want to transfer them as well.
For mac users, you can use
Sequel Pro
(free), which just provide the option to rename Databases. Though it doesn’t delete the old DB.once open the relevant DB just click:
Database
–>Rename database...
It is possible to rename all tables within a database to be under another database without having to do a full dump and restore.
However any triggers in the target db will not be happy. You’ll need to drop them first then recreate them after the rename.
Here is a batch file I wrote to automate it from the command line, but it for Windows/MS-DOS.
Syntax is rename_mysqldb database newdatabase -u [user] -p[password]
For your convenience, below is a small shellscript that has to be executed with two parameters: db-name and new db-name.
You might need to add login-parameters to the mysql-lines if you don’t use the .my.cnf-file in your home-directory. Please make a backup before executing this script.
The simplest method is to use HeidiSQL software. It’s free and open source. It runs on Windows and on any Linux with Wine (run Windows applications on Linux, BSD, Solaris and Mac OS X).
To download HeidiSQL, goto http://www.heidisql.com/download.php.
To download Wine, goto http://www.winehq.org/.
To rename a database in HeidiSQL, just right click on the database name and select ‘Edit’. Then enter a new name and press ‘OK’.
It is so simple.
I posed a question on Server Fault trying to get around downtime when restoring very large databases by using MySQL Proxy. I didn’t have any success, but I realized in the end what I wanted was RENAME DATABASE functionality because dump/import wasn’t an option due to the size of our database.
There is a RENAME TABLE functionality built in to MySQL so I ended up writing a simple Python script to do the job for me. I’ve posted it on GitHub in case it could be of use to others.
TodoInTX’s stored procedure didn’t quite work for me. Here’s my stab at it:
There is a reason you cannot do this. (despite all the attempted answers)
You’ll need to dump all object types in that database, create the newly named one and then import the dump. If this is a live system you’ll need to take it down. If you cannot, then you will need to setup replication from this database to the new one.
If you want to see the commands that could do this, @satishD has the details, which conveys some of the challenges around which you’ll need to build a strategy that matches your target database.
In MySQL Administrator do the following:
the old schema.
created in step 3.
Schema and select the new database
schema.
good, delete the old one.
Here is a one-line Bash snippet to move all tables from one schema to another:
The history command at the start simply ensures that the MySQL commands containing passwords aren’t saved to the shell history.
Make sure that
db_user
has read/write/drop permissions on the old schema, and read/write/create permissions on the new schema.ALTER DATABASE
is the proposed way around this by MySQL andRENAME DATABASE
is dropped.From 13.1.32 RENAME DATABASE Syntax:
This statement was added in MySQL 5.1.7, but it was found to be dangerous and was removed in MySQL 5.1.23.
in phpmyadmin you can easily rename the database
ask to drop old table and reload table data click OK in both
Your database is renamed
Here is a quick way to generate renaming sql script, if you have many tables to move.
I did it this way:
Take backup of your existing database. It will give you a db.zip.tmp and then in command prompt write following
If you are using phpMyAdmin you can go to the “operations” tab once you have selected the database you want to rename. Then go to the last section “copy database to” (or something like that), give a name, and select the options below. In this case, I guess you must select “structure and data” and “create database before copying” checkboxes and, finally, press the “go” button in that section.
By the way, I’m using phpMyAdmin in Spanish so I’m not sure what the names of the sections are in English.
This works for all databases and works by renaming each table with maatkit mysql toolkit
Use mk-find to print and rename each table. The man page has many more options and examples
If you have maatkit installed (which is very easy), then this is the simplest way to do it.
This is the batch script I wrote for renaming a database on Windows:
You can do it in two ways.
Neither TodoInTx’s solution nor user757945’s adapted solution worked for me on MySQL 5.5.16, so here is my adapted version:
Hope it helps someone who is in my situation! Note:
@sql_string
will linger in the session afterwards. I was not able to write this function without using it.I used following method to rename the database
take backup of the file using mysqldump or any DB tool eg heidiSQL,mysql administrator etc
Open back up (eg backupfile.sql) file in some text editor.
Search and replace the database name and save file.
4.Restore the edited sql file
If you use hierarchical views (views pulling data from other views), import of raw output from mysqldump may not work since mysqldump doesn’t care for correct order of views. Because of this, I wrote script which re-orders views to correct order on the fly.
It loooks like this:
Usage:
mysqldump -u username -v olddatabase -p | ./mysqldump_view_reorder.pl | mysql -u username -p -D newdatabase
If you prefer GUI tools and happen to have MySQL Workbench installed, you can use the built-in Migration Wizard
You guys are going to shoot me for this, and most probably this won’t work every time, and sure, it is against all logic blah blah… But what I just tried is… STOP the MySQL engine, log on as root and simply renamed the DB on the file system level….
I am on OSX, and only changed the case, from bedbf to BEDBF. To my surprise it worked…
I would not recommend it on a production DB. I just tried this as an experiment…
Good luck either way 🙂
I posted this How do I change the database name using MySQL? today after days of head scratching and hair pulling.
The solution is quite simple export a schema to a .sql file and open the file and change the database/schema name in the sql CREAT TABLE section at the top. There are three instances or more and may not be at the top of the page if multible schemas are saved to the file.
It is posible to edit the entire database this way but I expect that in large databases it could be quite a pain following all instances of a table property or index.
I).There is no way directly by which u can change the name of an existing DB
But u can achieve ur target by following below steps:-
1). Create newdb.
2). Use newdb.
3). create table table_name(select * from olddb.table_name);
By doing above, u r copying data from table of olddb and inserting those in newdb table. Give name of the table same.
II). RENAME TABLE old_db.table_name TO new_db.table_name;
In the case where you start from a dump file with several databases, you can perform a sed on the dump:
Then import your dump. Just ensure that there will be no name conflict.
Quickest and simplest solution i can give is…in MySql Workbench right click on your schema -> Click on create schema -> Enter name for that schema.
Drop your old schema with old name.
You are ready to rock….
NOTE :: For your local purpose only do this. Do not try at production database tables. Schema is created but there is no data in it. So be careful.
There are many really good answers here already but I do not see a PHP version. This copies an 800M DB in about a second.
Really, the simplest answer is to export your old database then import it into the new one that you’ve created to replace the old one. Of course, you should use phpMyAdmin or command line to do this.
Renaming and Jerry-rigging the database is a BAD-IDEA! DO NOT DO IT. (Unless you are the “hacker-type” sitting in your mother’s basement in the dark and eating pizza sleeping during the day.)
You will end up with more problems and work than you want.
So,
The extension on this file is .sql
— phpMyAdmin SQL Dump
— version 3.2.4
— http://www.phpmyadmin.net
— Host: localhost
— Generation Time: Jun 30, 2010 at 12:17 PM
— Server version: 5.0.90
— PHP Version: 5.2.6
SET SQL_MODE=”NO_AUTO_VALUE_ON_ZERO”;
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT /;
/!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS /;
/!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION /;
/!40101 SET NAMES utf8 */;
—
— Database:
mydatab_online
—
— Table structure for table
user
CREATE TABLE IF NOT EXISTS
user
(timestamp
int(15) NOT NULL default ‘0’,ip
varchar(40) NOT NULL default ”,file
varchar(100) NOT NULL default ”,PRIMARY KEY (
timestamp
),KEY
ip
(ip
),KEY
file
(file
)) ENGINE=MyISAM DEFAULT CHARSET=latin1;
—
— Dumping data for table
user
INSERT INTO
user
(timestamp
,ip
,file
) VALUES(1277911052, ‘999.236.177.116’, ”),
(1277911194, ‘999.236.177.116’, ”);
This will be your .sql file. The one that you’ve just exported.
Find it on your hard-drive; usually it is in
/temp
. Select the empty database that has the correct name (the reason why you are reading this).SAY: Import – GO
Connect your program to the correct database by entering it into what usually is a configuration.php file. Refresh the server (both. Why? Because I am a UNIX oldtimer, and I said so.
Now, you should be in good shape. If you have any further questions visit me on the web.
Simplest of all, open MYSQL >> SELECT DB whose name you want to change >> Click on “operation” then put New name in “Rename database to:” field then click “Go” button
Simple!
If you are using phpMyAdmin then you just go to the
mysql
folder in the xamp, close phpMyAdmin and just rename the folder you just see there as your database name and just restart your phpMyAdmin. You can see that that database as renamed.The simple way
or you can use online sql generator