Skip to content

Instantly share code, notes, and snippets.

@AndreasLazar
Created January 25, 2012 11:06
Show Gist options
  • Save AndreasLazar/1675836 to your computer and use it in GitHub Desktop.
Save AndreasLazar/1675836 to your computer and use it in GitHub Desktop.
lists all missing indexes of the current SQL Server
SELECT
DB_NAME(d.database_id) AS database_name
, LEFT (PARSENAME(d.statement, 1), 32) AS table_name
, ISNULL (d.equality_columns , '') AS equality_columns
, ISNULL (d.inequality_columns , '') AS inequality_columns
, ISNULL (d.included_columns , '') AS include_columns
, s.avg_total_user_cost -- This column represent the average total user cost each time when the user query was executed
, s.avg_user_impact -- This column represents the value in percentages. It informs us the amount of improvement which you can get if the index is created.
, s.unique_compiles
, s.user_seeks
, s.user_scans
, s.last_user_seek
, s.last_user_scan
, s.avg_total_user_cost * (s.avg_user_impact / 100.0) * (s.user_seeks + s.user_scans) AS est_improve
, 'CREATE NONCLUSTERED INDEX [index_name] ON ' + d.statement + ' (' + ISNULL (d.equality_columns,'') + CASE WHEN d.equality_columns IS NOT NULL AND d.inequality_columns IS NOT NULL THEN ',' ELSE '' END + ISNULL (d.inequality_columns, '') + ' ASC) ' + CASE WHEN d.included_columns IS NOT NULL THEN 'INCLUDE (' + d.included_columns + ')' ELSE '' END + ' WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]' AS create_index_statement
FROM sys.dm_db_missing_index_groups g
INNER JOIN sys.dm_db_missing_index_group_stats s ON s.group_handle = g.index_group_handle
INNER JOIN sys.dm_db_missing_index_details d ON g.index_handle = d.index_handle
ORDER BY est_improve DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment