Question

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   
Was it helpful?

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());
}

OTHER TIPS

Sorry but there is no MySQL comand for ALTER TABLE ny_table DROP ALL INDEXES EXCEPT PRIMARY KEY.

You would have to create a specific name for each index as it was created, and then create a loop to individually run an ALTER TABLE ... DROP INDEX SQL command for each index using the same names.

Note also that creating indexes is rather expensive - unless you are doing > ~200 queries that are optimized by the index, creating and deleting the index probably takes more time than is saved by using them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top