Search code examples
phpmysqlindexingsql-drop

MySQL command to drop all non-primary indexes of a table


Is there a MySQL command that can drop all the extra indexes except for the first one in a single table thus keeping only the primary index?

I can drop the second Post_Date index using the following MySQL command, but I am having problems dropping all the rest of them.

mysql_query("ALTER TABLE $TableName DROP INDEX Post_Date");

The extra Post_Date and Post_Date_x indexes are created in the beginning of the script, so I want to delete them at the end of the script using a MySQL command at the end of the script.

Keep in mind that _x in Post_Date_x and vary and could go from 1 to 10, or from 1 to 100. So a Loop or IF statement may be needed.

The MySQL command will be part of a PHP script

Thank you for your time.

Action  Keyname Type    Unique  Packed  Column  Cardinality Collation   Null    Comment
 Edit    Drop   PRIMARY BTREE   Yes No  id  830 A       
 Edit    Drop   Post_Date   BTREE   Yes No  Post_Date   830 A       
 Edit    Drop   Post_Date_2 BTREE   Yes No  Post_Date   830 A       
 Edit    Drop   Post_Date_3 BTREE   Yes No  Post_Date   830 A       
 Edit    Drop   Post_Date_4 BTREE   Yes No  Post_Date   830 A       
 Edit    Drop   Post_Date_5 BTREE   Yes No  Post_Date   830 A       
 Edit    Drop   Post_Date_6 BTREE   Yes No  Post_Date   830 A       
 Edit    Drop   Post_Date_7 BTREE   Yes No  Post_Date   830 A       
 Edit    Drop   Post_Date_8 BTREE   Yes No  Post_Date   830 A   

Solution

  • This should do it -

    $res = mysql_query("SHOW INDEX FROM `$TableName` WHERE `Key_name` LIKE 'Post_Date%'");
    
    while ($row = mysql_fetch_object($res)) {
        mysql_query("DROP INDEX `{$row->Key_name}` ON `{$row->Table}`") or die(mysql_error());
    }