Mysql – how can i rename all the tables in a database so the first character of each table’s name is removed

MySQL

how can i rename all the tables in a database so the first character of each table's name is removed. thanks! I'm using mysql 5.6.

Best Answer

Easy enough to do with SQL. You can send the output to a file then execute it once it's verified or just copy and paste the DDL statements back into your client to execute manually.

mysql> show tables;
+---------------------+
| Tables_in_mysqlslap |
+---------------------+
| tb1                 |
| tb2                 |
| tb3                 |
| tb4                 |
+---------------------+
4 rows in set (0.00 sec)

mysql> select 
  concat("RENAME TABLE ",table_name, " TO ", substring(table_name,2), ";") INTO OUTFILE '/var/lib/mysql-files/rename_tables.sql' 
  FROM information_schema.tables 
  WHERE table_schema = 'mysqlslap';
  Query OK, 4 rows affected (0.00 sec)

+--------------------------------------------------------------------------+
| concat("RENAME TABLE ",table_name, " TO ", substring(table_name,2), ";") |
+--------------------------------------------------------------------------+
| RENAME TABLE tb1 TO b1;                                                  |
| RENAME TABLE tb2 TO b2;                                                  |
| RENAME TABLE tb3 TO b3;                                                  |
| RENAME TABLE tb4 TO b4;                                                  |
+--------------------------------------------------------------------------+

mysql> RENAME TABLE tb1 TO b1;
Query OK, 0 rows affected (0.04 sec)

mysql> show tables;
+---------------------+
| Tables_in_mysqlslap |
+---------------------+
| b1                  |
| tb2                 |
| tb3                 |
| tb4                 |
+---------------------+
4 rows in set (0.00 sec)