Search code examples
mysqlddl

MySQL Drop Index's with loop?


I have a database with a lot of unscary indexes. I don't want to remove them all with one big query for time reasons. I'm not very familiar with query languages so is there a way to loop through the index list and remove all indexes with exception of PKs or is doing it the long way better/safer.


Solution

  • Thanks everyone for the helpful advice. I ended up taking Tadman's advice and used PHP to run a loop. here is the code in case anyone in the future has the same question/problem.

    --Query To get the index table of the table you wish to change
    $sql = "SHOW INDEX FROM `Your_Table_Name`";
    $Table = $conn->query($sql); 
    
    --while loop to get the rows in the index table
    while($Index=mysqli_fetch_array($Table)){
         $Name = $Index['Key_name']; --get name of index
    
         if($Name != 'PRIMARY'){ --see if index is primary Key
            -- if not run query to remove index
            $sql = "ALTER TABLE `Your_Table_Name` DROP INDEX `$Name`"; 
            $conn->query($sql);
         }
     }