Skip to content

Instantly share code, notes, and snippets.

@tadas-s
Created April 18, 2013 08:58
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 17 You must be signed in to fork a gist
  • Save tadas-s/5411299 to your computer and use it in GitHub Desktop.
Save tadas-s/5411299 to your computer and use it in GitHub Desktop.
MySQL database rename script
#!/bin/bash
# Disclaimer - make backups, use at your own risk.
#
# Based on this comment: http://stackoverflow.com/a/13944924/843067
# Views and stored procedures have to be done separately.
OLDDB="old_db_name"
NEWDB="new_db_name"
MYSQL="mysql -u root -pyour_password "
$MYSQL -e "CREATE DATABASE \`$NEWDB\`;"
for table in `$MYSQL -B -N -e "SHOW TABLES" $OLDDB`
do
$MYSQL -e "RENAME TABLE \`$OLDDB\`.\`$table\` to \`$NEWDB\`.\`$table\`"
done
# You *might not* want to uncoment line below since
# in case of problems while renaming tables
# you will lose all database
#mysql -e "DROP DATABASE \`$OLDDB\`;"
@scotteg
Copy link

scotteg commented Jul 4, 2013

Worked great, thanks!

@bean5
Copy link

bean5 commented Nov 24, 2013

I would like to see this handle view as well, but then again, it is just a gist. Worked great. Thanks!

@tadas-s
Copy link
Author

tadas-s commented Apr 10, 2014

@bean5 - never noticed that someone picked up this gist. I should probably keep maintaining it.

@UnconventionalMindset
Copy link

Thanks

@Pacerier
Copy link

Why do you use a for loop instead of mysqldump? :

mysqldump -R -uroot -p old_db|mysql -uroot -p new_db

@stubar
Copy link

stubar commented Mar 2, 2016

If the DB doesn't already exist
mysql -u root -p -e "create database new_db"; mysqldump -R -uroot -p old_db | mysql -uroot -p new_db

@jawkha
Copy link

jawkha commented Nov 29, 2017

@tadas-s thank you

@shivanshs9
Copy link

I've written a SQL script for the same since sql would definitely be faster than bash on a DB with a large number of tables.
To use it simply call the renameDatabase procedure.

CALL renameDatabase('old_name', 'new_name');

Tested on MariaDB and should work ideally on all RDBMS using InnoDB transactional engine.
Hopefully, it comes useful for others!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment