Computer >> Computer tutorials >  >> Programming >> MySQL

Rebuilding or Repairing MySQL Tables or Indexes


Changes to tables and indexes refers to how MySQL handles data types and character sets. The necessary table repairs or upgrades are reported by CHECK TABLE, mysqlcheck, or mysql_upgrade.

Rebuild a Table

There are many methods to rebuild a table. Some of them have been listed below −

  • Dump and Reload Method

  • ALTER TABLE Method

  • REPAIR TABLE Method

Let us understand each of them in brief −

Dump and Reload Method

If the tables are being rebuilt due to the fact that different versions of MySQL version can’t handle the tables after a binary (in-place) upgrade or download, then this dump and reload method needs to be used.

A table can be rebuilt by dumping and reloading it. This can be done by using the ‘mysqldump’ and creating a dump file and allowing mysql to reload the file. This can be done using the below commands −

mysqldump db_name t1 > dump.sql
mysql db_name < dump.sql

If all the tables have to be rebuilt in a single database, the name of the database can be specified without using any table name. It can be done using the below command −

mysqldump db_name > dump.sql
mysql db_name < dump.sql

If all the tables in all the databases have to be rebuilt, then the ‘− − all databases’ option has to be used. It can be done using the below command −

mysqldump --all-databases > dump.sql
mysql < dump.sql

ALTER TABLE Method

If a table needs to be rebuilt using the ALTER TABLE method, then a “null” alteration can be used. An ALTER TABLE statement can be used which changes the table so that it can use the storage engine. Let us take an example: Suppose TblName is an InnoDB table, the below statement can be used to rebuild the table −

ALTER TABLE TblName ENGINE = InnoDB;

REPAIR TABLE Method

The REPAIR TABLE method is only applicable to MyISAM, ARCHIVE, and CSV tables. The statement REPAIR TABLE can be used if the table checking operation suggests that the file has been corrupted or an upgrade is required. Let us take an example: In order to repair a MyISAM table, the below statement can be executed −

REPAIR TABLE TblName;

mysqlcheck −−repair provides command−line access to the REPAIR TABLE statement. This can be a more convenient means of repairing tables because you can use the −−databases to repair a specific table in a database or −−all−databases option to repair all tables in all databases. It can be done using the below commands −

mysqlcheck −−repair −−databases db_name ...
mysqlcheck −−repair −−all−databases