// SQL snippet

Generate CREATE INDEX statements from SQL Server's missing index DMVs

Every time the optimizer compiles a plan it wishes had an index, it writes the index down. This reads those notes back as ranked CREATE INDEX statements.

Main statement
SQL Server
다음도 지원
PostgreSQL MySQL

The task

When SQL Server fully optimizes a query and decides an index that does not exist would have made it cheaper, it records the wish in the missing index DMVs: which columns the query compared with = (equality), which with a range or <> (inequality), which it only selected (included), how many times a plan wanted it and how much cheaper the optimizer thinks the query would be. Reading them is the fastest way to a list of index candidates on a server you do not know. They are raw optimizer notes, though, not advice: they overlap, they ignore the indexes you already have, and following them blindly fills a table with near-duplicate indexes.

The snippet

Written for SQL Server. Versions for PostgreSQL and MySQL are under Variations.

SQL Server
SELECT TOP 25
    CAST(gs.avg_total_user_cost * gs.avg_user_impact / 100.0 * (gs.user_seeks + gs.user_scans) AS DECIMAL(18,1)) AS improvement_measure,
    gs.user_seeks + gs.user_scans AS uses,
    CAST(gs.avg_user_impact AS DECIMAL(5,1)) AS avg_impact_pct,
    gs.last_user_seek,
    d.statement AS table_name,
    d.equality_columns, d.inequality_columns, d.included_columns,
    'CREATE INDEX ' + QUOTENAME('ix_' + OBJECT_NAME(d.object_id, d.database_id) + '_missing_' + CAST(d.index_handle AS VARCHAR(10)))
      + ' ON ' + d.statement
      + ' (' + CONCAT_WS(', ', d.equality_columns, d.inequality_columns) + ')'
      + ISNULL(' INCLUDE (' + d.included_columns + ')', '') + ';' AS create_statement
FROM sys.dm_db_missing_index_details d
JOIN sys.dm_db_missing_index_groups g ON g.index_handle = d.index_handle
JOIN sys.dm_db_missing_index_group_stats gs ON gs.group_handle = g.index_group_handle
WHERE d.database_id = DB_ID()
ORDER BY improvement_measure DESC;

작동 방식

sys.dm_db_missing_index_details has one row per suggested index, with the columns already bracket-quoted and statement holding the three-part table name, which CREATE INDEX accepts for the current database. sys.dm_db_missing_index_groups links each suggestion to its statistics in sys.dm_db_missing_index_group_stats: user_seeks and user_scans count the compilations and executions that would have used it, avg_total_user_cost is the average plan cost of those queries and avg_user_impact the percentage the optimizer expects to save. Their product is the usual ranking figure; it is an estimate in optimizer cost units, useful for ordering, not a time. CONCAT_WS (SQL Server 2017 and later) joins the equality and inequality lists and skips whichever is NULL. The suggestions are kept in memory only: a restart, taking the database offline, or any metadata change on the table, including creating one of the suggested indexes, clears the table's entries. On the instance used to test this page, creating one index removed all four suggestions for that table. Reading the DMVs needs VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE on SQL Server 2022 and later).

Variations

SQL Server 2019 and later: which query wanted each index

SQL Server
SELECT TOP 20
    CAST(gsq.avg_total_user_cost * gsq.avg_user_impact / 100.0 * (gsq.user_seeks + gsq.user_scans) AS DECIMAL(18,1)) AS improvement_measure,
    gsq.user_seeks + gsq.user_scans AS uses,
    d.statement AS table_name,
    d.equality_columns, d.inequality_columns, d.included_columns,
    LEFT(SUBSTRING(st.text, gsq.last_statement_start_offset / 2 + 1,
         (CASE gsq.last_statement_end_offset WHEN -1 THEN DATALENGTH(st.text)
               ELSE gsq.last_statement_end_offset END - gsq.last_statement_start_offset) / 2 + 1), 200) AS query_text
FROM sys.dm_db_missing_index_group_stats_query gsq
JOIN sys.dm_db_missing_index_groups g ON g.index_group_handle = gsq.group_handle
JOIN sys.dm_db_missing_index_details d ON d.index_handle = g.index_handle
CROSS APPLY sys.dm_exec_sql_text(gsq.last_sql_handle) st
WHERE d.database_id = DB_ID()
ORDER BY improvement_measure DESC;

PostgreSQL: tables read mostly by sequential scans

PostgreSQL
SELECT schemaname, relname AS table_name,
       seq_scan, seq_tup_read,
       seq_tup_read / NULLIF(seq_scan, 0) AS avg_rows_per_seq_scan,
       COALESCE(idx_scan, 0) AS idx_scan,
       n_live_tup
FROM pg_stat_user_tables
WHERE seq_scan > 0
  AND n_live_tup > 10000
ORDER BY seq_tup_read DESC
LIMIT 20;

MySQL: statements that ran without a usable index

MySQL
SELECT db, exec_count, no_index_used_count, no_good_index_used_count,
       rows_examined_avg, rows_sent_avg, total_latency,
       LEFT(query, 120) AS query
FROM sys.statements_with_full_table_scans
WHERE db IS NOT NULL
ORDER BY no_index_used_count DESC
LIMIT 20;

Questions that come up

Can I run the generated statements as they are?

Not without reading them first. One query often produces several overlapping suggestions: in testing, one query produced both (customer_id, status, created_at) and the same key with INCLUDE (total), and a second query wanted (customer_id, created_at) INCLUDE (total). One index, (customer_id, status, created_at) INCLUDE (total), serves the first query; whether it is worth also building the second depends on how often that query runs. The suggestions also ignore your existing indexes, so check whether widening one of those does the job. The column order inside the equality list is not a recommendation, so put the column that narrows the rows most first, and the optimizer never suggests filtered indexes. Create the merged index, rerun the queries and compare their logical reads.

What do PostgreSQL and MySQL offer instead?

Neither records missing index wishes. In PostgreSQL, the variant finds the tables read mostly by full scans, and pg_stat_statements finds the queries behind them; two optional extensions go further: pg_qualstats records which columns WHERE clauses filter on, and hypopg creates hypothetical indexes that EXPLAIN takes into account without building anything. In MySQL, sys.statements_with_full_table_scans lists the statement digests that used no index (its query column is shortened for display; x$statements_with_full_table_scans has the full digest text), and sys.schema_tables_with_full_table_scans ranks tables by rows read in full scans. In both, EXPLAIN on the candidate query shows whether a new index is used.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.