
Indexes Are Not Magic: The Write, Storage and Selectivity Costs of Every Index
- كاتب موثّق
محتويات المقال
Status, CustomerId, CreatedAt, Total and Email. The cancelled-orders search got fast. The "pending" filter didn't change at all, checkout got slower, and the database grew. On a test copy in SQL Server 2022 with 900,000 orders, those five indexes made 10,000 single-row inserts take about 1 second instead of about 0.12 seconds, and the optimizer still refused to use the Status index for pending orders.
The common misconception
What actually happens
An index is a second copy, sorted differently
INSERT adds an entry to every index, every DELETE removes one, and an UPDATE changes each index that contains a modified column.
INSERT, UPDATE, DELETE and MERGE. PostgreSQL's docs add that indexes can prevent HOT (heap-only tuple) updates, the cheap kind that writes no new index entries because it changes no indexed column and fits on the same page.
Writes pay for every index
Primary key only: 105 to 138 ms, and about 2 MB of transaction log. Primary key plus five single-column indexes: 987 to 1,038 ms, and about 63 MB of log.
Id values always land at the end of the clustered index, but Email, CustomerId and Total arrive in random order, so their entries land in the middle of full pages, which split in two. Avoiding those splits is why Microsoft's guide recommends ever-increasing clustered keys. In the test, those 1% extra rows nearly doubled the three random-order indexes, while CreatedAt, which only grows, barely changed.
Storage and memory are costs too
Email index alone was 62 MB, because a string key is wide. Those pages get backed up with everything else, and they have to be in memory to be useful.
Selectivity decides whether the index is used at all
Status holds only Status and the row pointer, so for every match the engine still fetches the rest of the row: a in SQL Server, a heap fetch in PostgreSQL. A thousand lookups are cheap; a hundred thousand random ones cost more than reading the whole table in order, and the optimizer knows it from its statistics. Here's what it chose in the test, and what forcing the index with a hint cost:
Status filter (1,000,000 rows) | |||
|---|---|---|---|
'Cancelled', 0.1% of rows | |||
'Pending', 9.9% of rows | |||
'Delivered', 90% of rows |
Index queries, not columns
-- "Index every column the filters use"CREATE INDEX IX_Orders_Status ON dbo.Orders (Status);CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);CREATE INDEX IX_Orders_CreatedAt ON dbo.Orders (CreatedAt);CREATE INDEX IX_Orders_Total ON dbo.Orders (Total);CREATE INDEX IX_Orders_Email ON dbo.Orders (Email);-- Tested: 133 MB of indexes; 10,000 inserts took ~1.0 s, not ~0.12 s-- "My orders": WHERE CustomerId = @id ORDER BY CreatedAt DESCCREATE INDEX IX_Orders_Customer_CreatedAt ON dbo.Orders (CustomerId, CreatedAt DESC);-- Refund queue: 0.1% of rows, so index only those rowsCREATE INDEX IX_Orders_Cancelled ON dbo.Orders (CreatedAt) WHERE Status = 'Cancelled';-- Tested: 20 MB of indexes; 10,000 inserts took ~0.35 s-- Nonclustered indexes written to but never readSELECT OBJECT_NAME(i.object_id) AS table_name, i.name AS index_name, ISNULL(s.user_updates, 0) AS writesFROM sys.indexes AS iLEFT JOIN sys.dm_db_index_usage_stats AS s ON s.database_id = DB_ID() AND s.object_id = i.object_id AND s.index_id = i.index_idWHERE i.type_desc = 'NONCLUSTERED' AND i.is_unique = 0 AND OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1 AND ISNULL(s.user_seeks + s.user_scans + s.user_lookups, 0) = 0ORDER BY writes DESC;-- Indexes with no scans since statistics were last resetSELECT s.relname, s.indexrelname, s.idx_scanFROM pg_stat_user_indexes AS sJOIN pg_index AS i USING (indexrelid)WHERE s.idx_scan = 0 AND NOT i.indisunique;pg_stat_user_indexes columns in the docs and wasn't run for this article.
How to apply it in your project
Start from queries, not columns List the slow and frequent queries, then design one index per query shape. Before adding one, check whether widening an existing index would do; Microsoft's guide prefers that to near-duplicates. Check selectivity first Count how many rows each common filter value matches. An ordinary index won't be used for a value that covers a large share of the table; a filtered or partial index on the rare values might. Measure the write path Time inserts and updates on the table before and after the change, with production-sized data, not a development table with a few hundred rows. Review usage on a schedule After a full business cycle, drop indexes that are written but never read, and keep their CREATEstatements in case a rare report needed one.
Key takeaways
An index is a sorted copy maintained on every write that touches its columns: in the test, five single-column indexes made 10,000 inserts about 8 times slower. Random-order keys split pages: 1% more rows nearly doubled three of those indexes, which already took 133 MB next to a 94 MB table. Selectivity decides whether an index gets used: the Statusindex helped the 0.1% value and was skipped for the others, where forcing it read 25 to 227 times more pages.Index real query shapes, and use a filtered (partial) index when only a small subset of rows matters. Check usage counters over a full cycle and drop indexes that are written but never read.
التعليقات (0)