Add index to table if it does not exist
Try like this:
set @x := (select count(*) from information_schema.statistics where table_name = 'table' and index_name = 'IX_Table_XYZ' and table_schema = database());
set @sql := if( @x > 0, 'select ''Index exists.''', 'Alter Table TableName ADD Index IX_Table_XYZ (column1);');
PREPARE stmt FROM @sql;
EXECUTE stmt;
You can check if the index (by name of the index) exists by using this syntax
SELECT 1
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = 'yourschema' AND TABLE_NAME='yourtable' AND
INDEX_NAME='yourindex';
Then you could run it in a Stored Procedure like
IF (SELECT 1
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = 'yourschema' AND TABLE_NAME='yourtable' AND
INDEX_NAME='yourindex') != 1 THEN
Alter Table TableName ADD Index IX_Table_XYZ (column1);
END IF;
Based on @KayNelson's answer, for me in MySQL 5.7.16 the correct approach was to use IS NULL
instead of !=1
in the IF
condition.
So a snippet to conditionally add INDEX
to a table is:
IF (SELECT 1
FROM `INFORMATION_SCHEMA`.`STATISTICS`
WHERE `TABLE_SCHEMA` = 'yourschema'
AND `TABLE_NAME` = 'yourtable'
AND `INDEX_NAME` = 'yourindex') IS NULL THEN
ALTER TABLE `yourtable` ADD INDEX `yourindex` (`column1` ASC);
END IF;