How do I check if an index exists on a table field in MySQL?

前端 未结 10 1274
孤独总比滥情好
孤独总比滥情好 2020-12-12 16:55

I\'ve needed to Google this a couple times, so I\'m sharing my Q/A.

10条回答
  •  抹茶落季
    2020-12-12 17:19

    If you need the functionality if a index for a column exists (here at first place in sequence) as a database function you can use/adopt this code. If you want to check if an index exists at all regardless of the position in a multi-column-index, then just delete the part "AND SEQ_IN_INDEX = 1".

    DELIMITER $$
    CREATE FUNCTION `fct_check_if_index_for_column_exists_at_first_place`(
        `IN_SCHEMA` VARCHAR(255),
        `IN_TABLE` VARCHAR(255),
        `IN_COLUMN` VARCHAR(255)
    )
    RETURNS tinyint(4)
    LANGUAGE SQL
    DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT 'Check if index exists at first place in sequence for a given column in a given table in a given schema. Returns -1 if schema does not exist. Returns -2 if table does not exist. Returns -3 if column does not exist. If index exists in first place it returns 1, otherwise 0.'
    BEGIN
    
    -- Check if index exists at first place in sequence for a given column in a given table in a given schema. 
    -- Returns -1 if schema does not exist. 
    -- Returns -2 if table does not exist. 
    -- Returns -3 if column does not exist. 
    -- If the index exists in first place it returns 1, otherwise 0.
    -- Example call: SELECT fct_check_if_index_for_column_exists_at_first_place('schema_name', 'table_name', 'index_name');
    
    -- check if schema exists
    SELECT 
        COUNT(*) INTO @COUNT_EXISTS
    FROM 
        INFORMATION_SCHEMA.SCHEMATA
    WHERE 
        SCHEMA_NAME = IN_SCHEMA
    ;
    
    IF @COUNT_EXISTS = 0 THEN
        RETURN -1;
    END IF;
    
    
    -- check if table exists
    SELECT 
        COUNT(*) INTO @COUNT_EXISTS
    FROM 
        INFORMATION_SCHEMA.TABLES
    WHERE 
        TABLE_SCHEMA = IN_SCHEMA
    AND TABLE_NAME = IN_TABLE
    ;
    
    IF @COUNT_EXISTS = 0 THEN
        RETURN -2;
    END IF;
    
    
    -- check if column exists
    SELECT 
        COUNT(*) INTO @COUNT_EXISTS
    FROM 
        INFORMATION_SCHEMA.COLUMNS
    WHERE 
        TABLE_SCHEMA = IN_SCHEMA
    AND TABLE_NAME = IN_TABLE
    AND COLUMN_NAME = IN_COLUMN
    ;
    
    IF @COUNT_EXISTS = 0 THEN
        RETURN -3;
    END IF;
    
    -- check if index exists at first place in sequence
    SELECT 
        COUNT(*) INTO @COUNT_EXISTS
    FROM 
        information_schema.statistics 
    WHERE 
        TABLE_SCHEMA = IN_SCHEMA
    AND TABLE_NAME = IN_TABLE AND COLUMN_NAME = IN_COLUMN
    AND SEQ_IN_INDEX = 1;
    
    
    IF @COUNT_EXISTS > 0 THEN
        RETURN 1;
    ELSE
        RETURN 0;
    END IF;
    
    
    END$$
    DELIMITER ;
    

提交回复
热议问题