📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

The execution plan shows a green 'Missing Index' suggestion with a 95% estimated impact, and the missing index DMVs list dozens more. How do you read these suggestions, what are their limitations, and how do you decide which indexes to actually create?

Covers SQL Server missing index suggestions in plans and the sys.dm_db_missing_index_* DMVs: how they are generated, what impact means, their limitations (column order, overlap, no write cost, include bloat, reset on restart), and a workload-based process for turning them into real indexes.

Mid-Level Theory Intermediate dmv execution-plans indexes missing-indexes query-performance sql-server

🎯 Key points

  • Suggestions come from the optimiser during compilation when a better index would have reduced that plan's cost
  • Impact % is relative to that one plan's estimated cost, not real time saved
  • DMVs: sys.dm_db_missing_index_details, _groups, _group_stats, and _group_stats_query (2019+) for the query text
  • Column order is equality columns then inequality columns in table order, not by selectivity or ORDER BY
  • No awareness of existing indexes, overlap, write cost, filtered or columnstore indexes; INCLUDE lists often bloated
  • Data resets on restart, failover or index change and is capped at 600 groups
  • Start from the workload (top queries by total CPU and reads in Query Store) and use suggestions as clues for those queries
  • Validate after deploying: logical reads of target queries, write-path latency and sys.dm_db_index_usage_stats over a full business cycle

⏱ 30-second answer

The green missing index hint is the optimiser noting, while compiling that one plan, that an index would have reduced its estimated cost by that impact percentage. The missing index DMVs collect those notes across the workload with seek counts.

They're useful clues, not recommendations: column order is equality then inequality in table order, they ignore existing and overlapping indexes, never consider write cost, suggest bloated INCLUDE lists, and reset on restart.

I rank them by seeks × cost × impact, merge them with existing indexes, test the real query's logical reads and the write overhead, then check sys.dm_db_index_usage_stats after deploying. The trade-off: every index speeds some reads and slows every write.

🗣 Full answer (senior)

How I would answer this in an interview

"When the optimiser compiles a plan and notices that a particular index would have made this plan cheaper, it records a missing index suggestion. In the plan you see it in green with an impact percentage; across the server it accumulates in the missing index DMVs: sys.dm_db_missing_index_details for the columns, _group_stats for how many seeks or scans would have used it and the average cost and impact, and since SQL Server 2019 _group_stats_query for the query text. The impact is a percentage of that plan's estimated cost, so 95% on a query that runs once a day matters far less than 30% on one that runs 500 times a second.

The limitations matter more than the feature. Columns come out as equality columns, then inequality columns, then includes, each in table column order, not in the best order for selectivity or sorting. It doesn't know what indexes you already have, so it'll suggest (CustomerId) INCLUDE (Status) next to your existing (CustomerId, OrderDate). It never weighs insert and update cost, never suggests filtered or columnstore indexes, and often includes every column the query touched. It's capped at 600 groups and resets on restart, failover or when indexes on the table change.

The mistake I see is someone running a script that creates every missing index, and a month later the orders table has 25 indexes, inserts take three times longer and half the indexes are unused. My process is to rank by user seeks times average cost times impact, group suggestions per table, merge them with existing indexes, usually widening one, and test the actual query's logical reads and the write path before deploying. Afterwards I check usage stats to confirm it's used. Missing index suggestions tell you where it hurts, not what to build."


The DMVs

DMV What it gives
sys.dm_db_missing_index_details Table, equality, inequality and included columns
sys.dm_db_missing_index_groups Links details to group stats
sys.dm_db_missing_index_group_stats user_seeks, user_scans, avg_total_user_cost, avg_user_impact, last_user_seek
sys.dm_db_missing_index_group_stats_query (2019+) Query hash and stats per suggesting query

Limitations at a glance

Limitation Consequence
Per-plan, estimate-based Impact can be wildly off when estimates are wrong
Column order rule May not support ORDER BY or best seek prefix
No knowledge of existing indexes Duplicates and near-duplicates
No write cost Slower inserts, updates, deletes; more log and blocking
No filtered/columnstore suggestions Misses better designs
Reset on restart / index change, 600-group cap Incomplete picture

Production example

On a [ticketing] database the DMVs listed 34 suggestions for one table. Merging them gave three changes: widening one existing index with two INCLUDE columns, one new composite index with the date column second to support ORDER BY, and one filtered index on open tickets. The top five queries' reads fell by [90%] while insert latency rose only [4%]; creating all 34 would have added 34 B+ trees to maintain on every insert.

🔍 What the interviewer is checking

Checks whether the candidate treats missing index suggestions critically and can design indexes for a workload.

Green flags

  • Explains that impact is per-plan and estimate-based.
  • Lists the limitations: column order, overlap, write cost, resets.
  • Merges with existing indexes and measures reads and write cost.
  • Checks usage after deployment.

Red flags

  • Creates every suggestion.
  • Doesn't consider write overhead.
  • Has never looked at existing indexes before adding one.

📚 Learn in depth

1. Where suggestions come from

During optimisation, when the optimiser considers an access path and finds no suitable index, it estimates how much cheaper the plan would be with one, records the columns, and carries on with what exists. The suggestion is attached to the plan XML (MissingIndexGroup Impact="95.2") and aggregated in the DMVs.

compile query
   |
   +-- needs seek on (Status = @s, CreatedAt > @d) returning (CustomerId, Total)
   |
   +-- no suitable index -> record:
          equality:   [Status]
          inequality: [CreatedAt]
          include:    [CustomerId], [Total]
          impact:     95.2% of THIS plan's estimated cost

2. Why column order is naive

The rule is equality columns first, then inequality, each in table column order. That's often reasonable for seeks, but it ignores:

  • Which equality column is more selective or shared by other queries (to serve more queries with one index).
  • ORDER BY and GROUP BY, which a better order could satisfy without a sort.
  • The existing clustered key.

3. Measuring value

A common ranking metric is user_seeks * avg_total_user_cost * (avg_user_impact / 100). It's still built from estimates, so treat it as a priority list, not a decision.

4. Turning suggestions into a design

  1. Group by table.
  2. Compare with existing indexes (sys.indexes, sys.index_columns) and their usage (sys.dm_db_index_usage_stats).
  3. Merge: widen an existing index's INCLUDE list or reorder keys rather than adding a near-duplicate.
  4. Consider filtered indexes for status/soft-delete predicates and columnstore for analytics.
  5. Test: actual plan, logical reads for the target queries, and insert/update cost (reads and duration on the write path).
  6. Deploy with ONLINE = ON (Enterprise / Azure SQL), then confirm usage and remove what isn't used.

5. Automatic index management in Azure SQL

Azure SQL's automatic tuning has CREATE_INDEX and DROP_INDEX options (off by default for new servers). It uses the same signals but validates performance after creating, and reverts if it doesn't help. Teams that manage schema through migrations often keep it off and treat its recommendations as input, so the index ends up in source control.

Try it yourself

  1. Run a query filtering on a non-indexed column and find MissingIndexGroup in the plan XML.
  2. Query the four DMVs and match the suggestion to your query via _group_stats_query.
  3. Create the suggested index exactly as given, then design a better merged one and compare logical reads.
  4. Measure insert cost into the table before and after adding three suggested indexes.
  5. Restart a dev instance and confirm the DMVs are empty.

💻 Code

Rank suggestions with their query text, then compare with what already exists.

-- Ranked missing index suggestions with the queries asking for them (SQL Server 2019+ / Azure SQL)
SELECT TOP (25)
    OBJECT_NAME(d.object_id, d.database_id)                       AS table_name,
    d.equality_columns, d.inequality_columns, d.included_columns,
    gs.user_seeks, gs.avg_total_user_cost, gs.avg_user_impact,
    gs.user_seeks * gs.avg_total_user_cost * gs.avg_user_impact / 100 AS score,
    q.query_hash
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
LEFT JOIN sys.dm_db_missing_index_group_stats_query q ON q.group_handle = g.index_group_handle
WHERE d.database_id = DB_ID()
ORDER BY score DESC;

-- Existing indexes on the same table and whether they're used
SELECT i.name, i.type_desc,
       STRING_AGG(CASE WHEN ic.is_included_column = 0 THEN c.name END, ', ')
           WITHIN GROUP (ORDER BY ic.key_ordinal) AS key_cols,
       us.user_seeks, us.user_scans, us.user_lookups, us.user_updates
FROM sys.indexes i
JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
JOIN sys.columns c        ON c.object_id = ic.object_id AND c.column_id = ic.column_id
LEFT JOIN sys.dm_db_index_usage_stats us
       ON us.object_id = i.object_id AND us.index_id = i.index_id AND us.database_id = DB_ID()
WHERE i.object_id = OBJECT_ID('dbo.Tickets')
GROUP BY i.name, i.type_desc, us.user_seeks, us.user_scans, us.user_lookups, us.user_updates;

-- Suggested: (Status, CreatedAt) INCLUDE (CustomerId, Total, Subject, Body, AssignedTo)
-- Designed: filtered, narrower, supports ORDER BY CreatedAt DESC
CREATE INDEX IX_Tickets_Open_CreatedAt
    ON dbo.Tickets (CreatedAt DESC)
    INCLUDE (CustomerId, Total)
    WHERE Status = 'Open'
    WITH (ONLINE = ON);

If indexes live in EF Core migrations, declare the designed index there so schema stays in source control:

namespace Shop.Data.Configurations;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public sealed class TicketConfiguration : IEntityTypeConfiguration<Ticket>
{
    public void Configure(EntityTypeBuilder<Ticket> b)
    {
        b.HasIndex(t => t.CreatedAt)
         .HasDatabaseName("IX_Tickets_Open_CreatedAt")
         .IsDescending()
         .IncludeProperties(t => new { t.CustomerId, t.Total })
         .HasFilter("[Status] = 'Open'");
    }
}

⚠ Common mistakes

  • Mistake: Creating every suggested index. Why it is wrong: Duplicates, write amplification, bigger backups, more blocking. Instead: Merge suggestions into a small set designed for the workload.
  • Mistake: Trusting the impact percentage as real-world gain. Why it is wrong: It's relative to one plan's estimated cost. Instead: Weight by executions and measure logical reads.
  • Mistake: Copying the suggested column order. Why it is wrong: It's equality then inequality in table order, ignoring selectivity and ORDER BY. Instead: Choose order for seeks shared across queries and sort support.
  • Mistake: Accepting huge INCLUDE lists. Why it is wrong: The index becomes a second copy of the table. Instead: Include only columns needed by high-value queries.
  • Mistake: Reading the DMVs right after a restart or index change. Why it is wrong: They were reset and are incomplete. Instead: Look after a representative period, including month-end.
  • Mistake: Not checking existing indexes first. Why it is wrong: A small change to an existing index often covers the suggestion. Instead: Compare with sys.indexes and usage stats.
  • Mistake: Creating indexes in production by hand outside migrations. Why it is wrong: Environments drift and the next migration may drop it. Instead: Put indexes in source control (migrations or DACPAC).
  • Mistake: Testing only the read query in isolation and not watching production afterwards. Why it is wrong: The new index can change other queries' plans, add latency to the insert/update path, increase log volume and blocking at peak, and the index build itself takes locks and log space. Instead: Replay or load-test the write path in a production-sized environment, build with ONLINE = ON (and RESUMABLE = ON for big tables), and compare Query Store CPU and duration for the top queries and the write statements before and after.

🏛 Senior insight: trade-offs

Missing index suggestions are a symptom list. The senior job is index design across the workload: the fewest indexes that serve the most important queries, with the write cost understood. I start from the application rather than the DMV: which endpoints matter (checkout, search, month-end reporting), which queries they run (Query Store top consumers, tagged EF Core queries), and what latency target each has. Suggestions are then evidence for those specific queries. Every new index on a hot OLTP table needs a named query it serves, a measured benefit in logical reads and duration, and a measured write cost.

I also think in budgets: a write-heavy table might get five or six non-clustered indexes, so a new one may mean retiring another. After deploying, I check usage stats across a full business cycle and remove what isn't earning its keep. On Azure SQL, automatic index creation exists but most teams with migration-managed schemas keep it off and treat recommendations as input, so indexes stay in source control and code review.

Approach When it fits Cost When not to
Widen an existing index Suggestion overlaps an existing key Bigger index Index already very wide
New composite index Distinct, high-value access pattern Write and storage cost Write-heavy tables near index budget
Filtered index Predicate on a small subset (Open, not deleted) Parameterisation gotcha Queries can't match the filter
Columnstore Aggregations over many rows Batch-mode trade-offs, delta store Point lookups
Azure automatic CREATE_INDEX No DBA, low change control Schema drift from source control Migration-managed schemas

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions write cost or unused indexes Why: Checks index strategy on write-heavy tables and DMV caveats
    How to answer

    Every non-clustered index is another B-tree that each insert and delete (and updates to its columns) must modify, log and keep in memory, so a dozen indexes can multiply write cost several times. I design the set from the top queries by total cost in Query Store, then prune.

    • Unused: sys.dm_db_index_usage_stats, comparing seeks/scans/lookups with user_updates. Caveat: counters reset on restart or failover, so collect over a full business cycle.
    • Missing: the missing-index DMVs and plan hints. Caveats: they ignore write cost and overlap, give a poor column order, never suggest filtered or columnstore indexes, and reset too.
    • Keep unique and FK-supporting indexes even without reads. Remove by disabling first, then dropping.

    Trade-off: every index is a read optimisation paid for by every write.

  2. When: Candidate says the suggested column order may be wrong Why: Checks composite index column order reasoning
    How to answer

    A composite index is a B+ tree sorted by the first column, then by the second within each first value, like a phone book sorted by surname then first name.

    • Leftmost-prefix rule: SQL Server can seek only when the query constrains the leading column(s). (CustomerId, OrderDate, Status) supports CustomerId = @c, CustomerId = @c AND OrderDate >= @d, but not OrderDate >= @d alone (that scans; SQL Server has no skip-scan).
    • Put equality columns first, then the range column. After a range, later columns can only be filtered as a residual predicate, not seeked.
    • The order also lets the index return rows already sorted, avoiding a Sort.

    Trade-off: one well-ordered index can serve several queries; the wrong order serves none.

  3. When: Candidate talks about INCLUDE columns Why: Checks covering index trade-offs
    How to answer

    A key lookup happens when a non-clustered index finds the rows but lacks some columns the query needs, so SQL Server goes back to the clustered index for each row (a RID lookup on a heap). Each one is 3–4 random logical reads.

    A covering index holds every column the query references, so no lookup is needed.

    • Key columns are sorted and searchable: use them for WHERE, JOIN and ORDER BY.
    • INCLUDE columns sit only in the leaf level: not sorted, not counted in the key size limit, cheaper to maintain. Use them for columns that are only selected.

    Lookups hurt when they run for thousands of rows; past the tipping point the optimiser scans instead. Trade-off: covering speeds a query but widens the index and every write.

🛠 Real-world problems: how you handle them

Blindly created missing indexes slow down order inserts
Situation
An [e-commerce] database on [SQL Server 2022] had a scheduled script, added by a previous team, that created the top missing index suggestions weekly. The Orders table had grown to [27] non-clustered indexes.
Signals
Checkout latency p95 rose from [180 ms] to [650 ms]; insert duration on Orders in Query Store tripled; transaction log growth and backup size increased; occasional blocking on Orders during peak.
Investigation
`sys.dm_db_index_usage_stats` showed [11] indexes with zero seeks or scans but millions of updates since the last restart. Comparing key columns found [6] near-duplicates differing only in INCLUDE lists. The insert plan showed an index maintenance operator per index.
Resolution
Disabled the script. Dropped unused and duplicate indexes after a month of usage monitoring (scripted, with the definitions saved for rollback), and merged the remaining suggestions into [4] designed indexes. All changes went into the migration project.
Prevention
Index changes require a named query, before/after reads and a write-cost check in the PR template. A monthly report lists unused indexes and new missing index suggestions for review rather than automatic creation.

How to tell it (STAR)

**S:** Checkout on our [e-commerce] site had slowed from [180 ms] to [650 ms] at p95, and inserts into Orders had tripled in duration. **T:** I was asked to find the cause. **A:** The Orders table had 27 indexes, because a weekly script created whatever the missing index DMVs suggested. Usage stats showed 11 were never read and 6 were near-duplicates. I stopped the script, monitored usage for a month, dropped the dead and duplicate indexes with rollback scripts ready, and merged what was left into 4 designed indexes in our migrations. **R:** Checkout p95 dropped back to [200 ms], log volume fell by about [40%], and index changes now go through review with measured benefit.

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me