15

I want to DROP INDEX in mysql with option IF EXISTS but I have found nothing that make it works.

DROP INDEX IF EXISTS index_name ON table_name;

Anyone has any hint?

elijahcarrel
  • 3,787
  • 4
  • 17
  • 21
Rayuth You
  • 151
  • 1
  • 1
  • 5

3 Answers3

11

I do not see any straight-forward way to DROP INDEX using IF EXISTS. As a workaround, I wrote the following Procedure, which works for me.

CREATE PROCEDURE `DropIndexIfExists`(
    IN i_table_name VARCHAR(128),
    IN i_index_name VARCHAR(128)
    )
    BEGIN

    SET @tableName = i_table_name;
    SET @indexName = i_index_name;
    SET @indexExists = 0;

    SELECT 
        1
    INTO @indexExists FROM
        INFORMATION_SCHEMA.STATISTICS
    WHERE
        TABLE_NAME = @tableName
            AND INDEX_NAME = @indexName;

    SET @query = CONCAT(
        'DROP INDEX ', @indexName, ' ON ', @tableName
    );
    IF @indexExists THEN
        PREPARE stmt FROM @query;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;
    END
Sergey Romanov
  • 2,949
  • 4
  • 23
  • 38
Man
  • 2,720
  • 2
  • 13
  • 21
  • 2
    you could put your `SET @query...` inside the `IF`. Nitpick, but why would it run otherwise ? :p – Drew Oct 04 '16 at 21:06
  • update if multiple databases : `... SELECT 1 INTO @indexExists FROM INFORMATION_SCHEMA.STATISTICS WHERE INDEX_SCHEMA = database() AND TABLE_NAME = @tableName AND INDEX_NAME = @indexName LIMIT 1; ... ` – asimov May 15 '23 at 09:26
6

Try this,

create procedure DeleteIndex()
begin

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.STATISTICS  WHERE TABLE_NAME = 'TableName'
            AND INDEX_NAME = 'IndexName' AND INDEX_SCHEMA='DbName') THEN
   ALTER TABLE  TableName DROP index THead2;
END IF;
END
Prakash S
  • 85
  • 8
-3

This is how you can drop index if exists in Laravel:

Schema::table("table_name", function (Blueprint $table) {
    $indexes = DB::connection()->getDoctrineSchemaManager()->listTableIndexes("table_name");
    foreach ($indexes as $key => $val) {
        if ($key == "index_name") {
            $table->dropIndex("index_name");
        }
    }
});
Ilyich
  • 4,966
  • 3
  • 39
  • 27