How can I employ “if exists” for creating or dropping an index in MySQL?

Here is my 4 liner:

set @exist := (select count(*) from information_schema.statistics where table_name="table" and index_name="index" and table_schema = database());
set @sqlstmt := if( @exist > 0, 'select ''INFO: Index already exists.''', 'create index i_index on tablename ( columnname )');
PREPARE stmt FROM @sqlstmt;
EXECUTE stmt;

Leave a Comment