Sunday, February 23, 2020

Find require /missing index on tables

Identifying and Recommending Missing Indexes for Better SQL Server Performance

When optimizing SQL Server performance, identifying missing indexes can be an effective way to reduce query costs and improve response times. However, analyzing index recommendations can be resource-intensive. It is often best to schedule this analysis during off-peak hours and store the results for further in-depth review.

SQL Query to Detect Missing Indexes

The following SQL query calculates a metric to prioritize potential missing indexes based on their impact and usage. It also generates the recommended CREATE INDEX statements for implementation:


SELECT
    migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (migs.user_seeks + migs.user_scans) AS improvement_measure,
    'CREATE INDEX [IX_' + CONVERT(VARCHAR, mig.index_group_handle) + '_' + CONVERT(VARCHAR, mid.index_handle) + '_' + LEFT(PARSENAME(mid.STATEMENT, 1), 32) + ']' + 
    ' ON ' + mid.STATEMENT + 
    ' (' + ISNULL(mid.equality_columns, '') + 
    CASE 
        WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL THEN ',' 
        ELSE '' 
    END + ISNULL(mid.inequality_columns, '') + ') ' + 
    ISNULL(' INCLUDE (' + mid.included_columns + ')', '') AS create_index_statement,
    migs.*,
    mid.database_id,
    mid.[object_id]
FROM
    [sys].dm_db_missing_index_groups AS mig
INNER JOIN 
    [sys].dm_db_missing_index_group_stats AS migs 
    ON migs.group_handle = mig.index_group_handle
INNER JOIN 
    [sys].dm_db_missing_index_details AS mid 
    ON mig.index_handle = mid.index_handle
WHERE
    migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * 
    (migs.user_seeks + migs.user_scans) > 10
ORDER BY 
    migs.avg_total_user_cost * migs.avg_user_impact * 
    (migs.user_seeks + migs.user_scans) DESC;

Why Missing Indexes Matter

Missing indexes can significantly degrade database performance by forcing SQL Server to perform expensive scans instead of efficient seeks. By regularly reviewing and applying index recommendations, you can ensure your database runs smoothly and efficiently, especially under heavy load.

Popular Posts