Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make DROP INDEX IF EXISTS for mysql?

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?

like image 308
Rayuth You Avatar asked Oct 04 '16 09:10

Rayuth You


People also ask

How do you remove indexes from a table?

Right-click the table that contains the index you want to delete and click Design. On the Table Designer menu, click Indexes/Keys. In the Indexes/Keys dialog box, select the index you want to delete. Click Delete.

How do you drop a composite index?

Try the following command: show index from `my_answers`; then inspect the key name of your index and drop it by its name.

Does DROP TABLE Remove index?

DROP TABLE always removes any indexes, rules, triggers, and constraints that exist for the target table. However, to drop a table that is referenced by a view or a foreign-key constraint of another table, CASCADE must be specified.


2 Answers

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
like image 134
Prakash S Avatar answered Oct 13 '22 06:10

Prakash S


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
like image 37
Man Avatar answered Oct 13 '22 05:10

Man