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

📚 Interview question

You own a write-heavy SQL Server table (orders, events or telemetry) that has accumulated a dozen indexes. How do you decide which indexes it should have? Explain the write cost of each index, how you find unused and missing indexes with DMVs, and the caveats of those DMVs.

Covers the per-index write, log, memory and blocking cost, building an index set from real query patterns, finding unused indexes with sys.dm_db_index_usage_stats and missing indexes with the missing-index DMVs and Query Store, their caveats (resets, no column-order or write-cost awareness), safe removal by disabling first, and Azure SQL automatic tuning.

Senior Theory Advanced azure-sql dmv index-strategy indexes query-store sql-server

🎯 Key points

  • Each NC index adds a B-tree modification, log records, buffer pool pages and lock or latch contention per write
  • More indexes = more lock acquisition orders under concurrent writes, so more blocking and deadlocks
  • Design from the top queries by total cost (Query Store), not from individual suggestions
  • sys.dm_db_index_usage_stats: reads vs user_updates; counters reset on restart, failover and database offline, so persist snapshots over a business cycle
  • Missing index DMVs ignore write cost and overlap, don't order key columns well, never suggest filtered or columnstore, and reset on restart
  • Keep unique and FK-supporting indexes even with no reads; consolidate left-prefix duplicates
  • Remove safely: script, ALTER INDEX ... DISABLE, watch, then drop; check index hints first
  • Azure SQL automatic tuning: CREATE_INDEX/DROP_INDEX can be set to apply automatically with validation and rollback (off by default); FORCE_LAST_GOOD_PLAN is on by default

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I start from the fact that every non-clustered index is a separate B-tree that has to be maintained on the write path. An insert into a table with twelve indexes is thirteen B-tree inserts, each logged, each needing pages in the buffer pool, and each a place for latch contention and deadlocks. On a write-heavy table that shows up as insert latency, log throughput limits in Azure SQL, longer backups and slower availability group redo. So the question is never 'would this index help a query?' It's 'is the read benefit worth the cost on every write?'

My process: pull the top queries for the table from Query Store by total CPU and duration, write down each query's equality, range and sort columns, and design the smallest set of composite indexes whose prefixes cover them, with INCLUDE only for the hot ones. Then prune with sys.dm_db_index_usage_stats: indexes with zero seeks, scans and lookups but millions of updates are candidates. The caveat is that those counters reset when the instance restarts, when the database goes offline or an Azure SQL failover happens, so I collect snapshots over a full business cycle including month-end, otherwise the month-end report's index looks unused. I never drop unique indexes, because they enforce rules, or indexes on foreign key columns, because deletes on the parent rely on them.

The missing-index DMVs are useful as hints, not as instructions: they suggest an index per query, ignore what already exists, ignore write cost, list key columns as equality then inequality without thinking about order, and never suggest filtered or columnstore indexes. The mistake I see is scripting every suggestion. For example, at [company] we [consolidated fourteen indexes on an events table into six; insert p95 dropped from [12] to [4] ms and log generation by [45]% with no read regressions in Query Store]. And I remove indexes by disabling them first, so rolling back is a rebuild rather than a guess at the old definition."


What one more index costs

Cost Where you see it
Extra B-tree modification per insert/delete (and per update of its columns) Insert/update duration, sys.dm_db_index_operational_stats
Log records Log throughput, Azure SQL log rate cap, AG redo and backup size
Buffer pool pages Page life expectancy, memory pressure
Locks and latches on more structures Blocking, deadlocks between index access orders
Maintenance and storage Rebuild/statistics time, backup size
Optimiser choice More plans to consider; plan changes after adding or dropping

DMV caveats

DMV Tells you Caveat
sys.dm_db_index_usage_stats Seeks, scans, lookups, updates since last reset Reset on restart, failover, offline/detach; a scan counts once regardless of size
sys.dm_db_index_operational_stats Leaf inserts, splits, lock and latch waits Resets when metadata leaves the cache
sys.dm_db_missing_index_* Suggested columns and estimated impact Per query, overlapping, no write cost, no filtered/columnstore, max 600 groups, reset on restart
sys.dm_db_missing_index_group_stats_query (2019+) Which query produced a suggestion Same reset caveat
Query Store Persistent query cost history Must be enabled (on by default in Azure SQL and SQL Server 2022 new databases)

Production example

A telemetry table took 4,000 inserts a second with 14 non-clustered indexes. Four had no reads over 35 days of snapshots, three were left-prefix duplicates of others, and one was a missing-index suggestion covering a report that ran once a week. Dropping eight (after a two-week disable period) cut insert p95 from 12 ms to 4 ms, log generation by 45% and the table's size by 38%.

🔍 What the interviewer is checking

Checks whether the candidate manages indexes as a cost-benefit portfolio with evidence, and knows the traps in the DMVs everyone quotes.

Green flags

  • Quantifies write, log, memory and locking costs per index
  • Designs from Query Store top queries and consolidates prefixes
  • Knows usage stats reset and collects over a business cycle
  • Lists missing-index DMV caveats and removes indexes by disabling first

Red flags

  • "More indexes = faster"
  • Creates every missing-index suggestion
  • Drops unique or FK indexes because they have no seeks

📚 Learn in depth

1. The write path with many indexes

INSERT INTO dbo.Events (...)
  -> clustered index insert          (log record)
  -> IX_Events_DeviceId insert        (log record)
  -> IX_Events_Type_CreatedAt insert  (log record)
  -> ... x N non-clustered indexes
  -> commit: flush log to disk (write-ahead logging)

Updates touch only indexes containing a modified column (key or INCLUDE), unless the update changes the clustered key, which updates every index. Deletes touch every index. Each modification needs the page in memory, a latch, possibly a page split, and a lock on the key, so more indexes also means more ways for two transactions to take locks in different orders and deadlock.

2. Building the set from workload

  1. Query Store: top queries touching the table by total CPU, duration and executions over at least two weeks.
  2. For each: equality columns, range column, sort, selected columns.
  3. Group queries sharing leading columns; one composite index per group.
  4. INCLUDE only for queries where lookups are a large share of a hot query's cost.
  5. Check write frequency: on 4,000 inserts/s, each index needs a strong justification.

3. Usage statistics in practice

user_seeks, user_scans, user_lookups count operations, not rows. user_updates counts write operations. Because the DMV resets, persist snapshots (e.g. daily into a table) and sum across them. Historically, some SQL Server 2012-2016 builds also reset an index's row on rebuild; current versions do not, but treat old numbers with care. On availability groups, readable secondaries have their own counters: an index used only by reports on the secondary looks unused on the primary.

4. Missing index suggestions

The optimiser records a suggestion when it thinks an index would have helped a plan. Equality columns, inequality columns and included columns are listed by column id, not by best order. Two similar queries produce two overlapping suggestions. avg_user_impact is the optimiser's own estimated cost reduction, not measured time. Use them to find candidate patterns, then design one consolidated index.

5. Removing safely

  • Script the definition, then ALTER INDEX ... DISABLE (keeps metadata, frees the data; for non-clustered indexes only, because disabling a clustered index makes the table unreadable).
  • Search code for index hints first. A query with WITH (INDEX(name)) fails with error 308 when the index does not exist and error 315 when it is disabled, so a hinted query breaks outright instead of just slowing down.
  • Watch Query Store and application errors for a business cycle, then drop, or re-enable with ALTER INDEX ... REBUILD.

6. Azure SQL automatic tuning

Azure SQL Database can recommend CREATE INDEX and DROP INDEX and, if you enable those options, apply them automatically, validate the effect and roll back regressions. They are off by default for new databases, while FORCE_LAST_GOOD_PLAN is on. Teams that manage indexes through EF Core migrations usually keep automatic index changes off to avoid drift between the model and the database, and review the recommendations instead.

Try it yourself

  1. Create a table with 1 and then 10 non-clustered indexes; time 500,000 inserts in each case and compare the log generated (sys.dm_db_log_stats before and after in a test database).
  2. Snapshot sys.dm_db_index_usage_stats hourly into a table for a week on a test workload.
  3. Run a mixed workload and compare the missing-index suggestions with what you would design by hand.
  4. Disable an index, run the workload, and check Query Store for regressed queries; then rebuild it.
  5. Grep your codebase for WITH (INDEX( and FORCESEEK before removing any index.

💻 Code

Measure read value against write cost per index, and persist usage across restarts.

-- Reads vs writes per index (since the last reset: check sqlserver_start_time first)
SELECT sqlserver_start_time FROM sys.dm_os_sys_info;

SELECT i.name AS index_name, i.is_unique, i.is_primary_key,
       ISNULL(us.user_seeks, 0) + ISNULL(us.user_scans, 0) + ISNULL(us.user_lookups, 0) AS reads,
       ISNULL(us.user_updates, 0) AS writes,
       ps.used_page_count * 8 / 1024 AS size_mb
FROM sys.indexes AS i
LEFT JOIN sys.dm_db_index_usage_stats AS us
       ON us.database_id = DB_ID() AND us.object_id = i.object_id AND us.index_id = i.index_id
JOIN sys.dm_db_partition_stats AS ps ON ps.object_id = i.object_id AND ps.index_id = i.index_id
WHERE i.object_id = OBJECT_ID(N'dbo.Events') AND i.index_id > 1
ORDER BY reads, writes DESC;

-- Persist daily so a restart or failover does not erase the evidence
INSERT INTO dba.IndexUsageSnapshot (captured_at, object_id, index_id, user_seeks, user_scans, user_lookups, user_updates)
SELECT SYSUTCDATETIME(), object_id, index_id, user_seeks, user_scans, user_lookups, user_updates
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID();

-- Missing index suggestions with the query that produced them (SQL Server 2019+ / Azure SQL)
SELECT TOP (20) d.statement AS table_name, d.equality_columns, d.inequality_columns, d.included_columns,
       gs.user_seeks, gs.avg_user_impact, SUBSTRING(st.text, 1, 200) AS query_start
FROM sys.dm_db_missing_index_details AS d
JOIN sys.dm_db_missing_index_groups AS g ON g.index_handle = d.index_handle
JOIN sys.dm_db_missing_index_group_stats AS gs ON gs.group_handle = g.index_group_handle
JOIN sys.dm_db_missing_index_group_stats_query AS q ON q.group_handle = g.index_group_handle
CROSS APPLY sys.dm_exec_sql_text(q.last_sql_handle) AS st
WHERE d.database_id = DB_ID()
ORDER BY gs.user_seeks * gs.avg_user_impact DESC;

-- Remove safely: disable first (definition kept), drop after a business cycle
ALTER INDEX IX_Events_Type ON dbo.Events DISABLE;
-- Roll back if needed:
-- ALTER INDEX IX_Events_Type ON dbo.Events REBUILD WITH (ONLINE = ON);

If indexes are owned by EF Core migrations, the model must change too, or the next migration will recreate the dropped index.

namespace Telemetry.Data;

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

public sealed class DeviceEvent
{
    public long EventId { get; set; }
    public int DeviceId { get; set; }
    public short EventType { get; set; }
    public DateTime CreatedAt { get; set; }
}

public sealed class DeviceEventConfiguration : IEntityTypeConfiguration<DeviceEvent>
{
    public void Configure(EntityTypeBuilder<DeviceEvent> b)
    {
        b.HasKey(e => e.EventId);

        // One consolidated index serves: by device, by device + time range, latest per device.
        b.HasIndex(e => new { e.DeviceId, e.CreatedAt })
         .HasDatabaseName("IX_Events_Device_CreatedAt");

        // Removed after 35 days with zero reads: (DeviceId), (EventType), (CreatedAt, DeviceId).
        // Keep this list in the configuration so nobody re-adds them from a missing-index hint.
    }
}

⚠ Common mistakes

  • Mistake: Creating every missing-index suggestion. Why it is wrong: suggestions overlap, ignore write cost and have poor column order. Instead: treat them as hints and design consolidated indexes from Query Store's top queries.
  • Mistake: Dropping indexes based on usage stats collected since last Tuesday's patch reboot. Why it is wrong: counters reset, so monthly and yearly jobs look like they never read the index. Instead: persist snapshots over a full business cycle.
  • Mistake: Dropping a unique index because it has no reads. Why it is wrong: it enforces a business rule; duplicates arrive next. Instead: keep unique indexes, or replace with a unique constraint deliberately.
  • Mistake: Dropping the index on a foreign key column. Why it is wrong: deletes or key updates on the parent scan the child and block. Instead: keep FK-supporting indexes on tables with parent deletes.
  • Mistake: Dropping straight away. Why it is wrong: rollback means guessing the definition under pressure. Instead: script and DISABLE first, drop later.
  • Mistake: Ignoring readable secondaries. Why it is wrong: usage on a reporting replica does not show on the primary. Instead: check usage stats on every replica.
  • Mistake: Dropping an index in the database but not in the EF Core model. Why it is wrong: the next migration recreates it. Instead: change the model and generate the migration.
  • Mistake: Forgetting index hints in code. Why it is wrong: a hinted query fails outright when the index is gone. Instead: search for WITH (INDEX( before disabling.

🏛 Senior insight: trade-offs

On write-heavy tables I aim for the fewest indexes that keep the top queries' plans healthy, and I make that a documented, reviewed decision, because indexes accumulate one well-meant hotfix at a time and nobody ever removes them. Ownership matters: if migrations own the schema, index changes go through the model and code review like any other change, and Azure SQL's automatic index creation stays off to avoid drift.

Concurrency is where index sprawl hurts most. Under many parallel writers, each extra index is another structure whose pages need latches and whose keys need locks; two transactions that touch the same rows through different indexes can take those locks in different orders and deadlock, and hot pages at the end of ever-increasing index keys create PAGELATCH_EX contention. When I see deadlock graphs on a write-heavy table, the number and shape of its indexes is one of the first things I check.

To keep the decision visible I record it: a short ADR or a table-level note listing each index, the queries it serves (Query Store query ids), and the indexes deliberately removed and why. New index requests go through a pull request with Query Store evidence and an estimate of the write impact, reviewed by whoever owns the table.

Option When it fits Cost When not to
Consolidated composite indexes from Query Store Ongoing tuning of a busy table Analysis time Workload unknown or too new
Missing-index DMV suggestions Finding candidate patterns Overlap, write cost ignored Applied blindly
Azure SQL automatic index tuning Small teams without DBA time, no migration ownership Drift from the model, less control Schema owned by EF Core migrations
Separate reporting copy or columnstore Heavy reports on a write-heavy table Another structure or pipeline A couple of point queries

Note that availability group secondaries have the same indexes as the primary, so moving reports to a readable secondary does not remove their write cost; a separate reporting copy (or a columnstore) does.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions merging left-prefix duplicates. Why: Checks they can consolidate indexes by column order.
    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.

  2. When: Candidate says they keep FK-supporting indexes. Why: Checks they know why foreign key indexes matter for deletes.
    How to answer

    When you delete a parent row, SQL Server must check every child table that references it. If the child's foreign key column has no index, each check is a table scan, and the delete's locks are held for the whole long statement. A large delete also escalates to a table lock after about 5,000 locks, blocking everyone.

    I'd confirm it from the actual plan (a scan of the child under the FK check, huge logical reads) and the blocking chain (sys.dm_exec_requests, sp_WhoIsActive). The fix: index the FK columns, delete in small batches with short transactions, and avoid wide cascades. Separately, constraints created WITH NOCHECK are untrusted, so the optimiser cannot use them; re-validate with WITH CHECK CHECK CONSTRAINT once the data is clean.

  3. When: Candidate mentions covering only hot queries. Why: Checks when INCLUDE columns earn their write cost.
    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

Insert latency and log rate throttling from index sprawl on an events table
Situation
An [IoT telemetry] platform on Azure SQL (Business Critical, [16] vCores) ingested [4,000] events a second into one table that had accumulated [14] non-clustered indexes over [3] years of hotfixes and missing-index suggestions.
Signals
Ingestion p95 rose from [4] ms to [12] ms; Azure SQL showed `LOG_RATE_GOVERNOR` waits and log write percentage near 100% at peak; an ingestion queue backlog built up every evening.
Investigation
Wait stats (`sys.dm_db_wait_stats`) pointed to log rate governance. `sys.dm_db_index_operational_stats` showed every index taking leaf inserts. Daily snapshots of `sys.dm_db_index_usage_stats` over [35] days (spanning month-end) showed four indexes with zero reads; a prefix comparison found three left-prefix duplicates; Query Store showed one wide covering index served a weekly report only.
Resolution
Immediate: scaled up temporarily to raise the log rate cap. Real fix: scripted and disabled eight indexes in two waves a week apart, monitored Query Store for regressions (none), then dropped them through an EF Core migration; moved the weekly report to a columnstore copy refreshed nightly.
Prevention
Index changes on the table require a pull request with Query Store evidence; a monthly report of reads versus writes per index from the persisted snapshots; an alert on log write percentage above 80%; Azure SQL automatic index creation kept off to avoid drift.

How to tell it (STAR)

**S:** At [company] our telemetry ingestion was slowing every evening and Azure SQL was throttling log writes. **T:** I had to cut write cost without breaking any reads. **A:** Wait stats pointed at the log rate cap, so I looked at the [14] indexes on the events table, persisted usage stats across a full month, found eight that were unused, duplicated or served one weekly report, disabled them in two waves while watching Query Store, then dropped them through a migration and moved the report to a columnstore copy. **R:** Insert p95 went from [12] ms to [4] ms, log generation dropped about [45]%, and we scaled back down to the original tier.

↩ Usually asked after

More in Indexes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me