الانتقال إلى المحتوى
قواعد البياناتIndexing· 7 دقائق للقراءة

Indexes Are Not Magic: The Write, Storage and Selectivity Costs of Every Index

Every index is a sorted copy the database keeps in sync on every write, and the optimizer skips it when the filter isn't selective enough.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

The admin search for orders was slow, so a migration added an index on every column the filters use: 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

The belief: an index on a column makes queries on that column faster, and all it costs is a bit of disk space.

It survives because it's half true. On a selective filter, an index really does turn a full table scan into a handful of page reads: in the test, finding the 1,000 cancelled orders among 1,000,000 took 3,077 logical reads through the index, against 12,146 for a full scan. Tutorials show exactly that query. The costs land somewhere else: in other endpoints that write to the table, in the nightly import, in the backup. No read query's plan shows the price of the indexes it didn't use.

What actually happens

An index is a second copy, sorted differently

A B-tree index stores the indexed values in sorted order, each with a pointer back to its row. In SQL Server, that pointer is the clustered index key, or a row ID when the table is a heap. In PostgreSQL, every index is a secondary structure stored apart from the table's heap. Either way, the database keeps each copy in sync: every INSERT adds an entry to every index, every DELETE removes one, and an UPDATE changes each index that contains a modified column.

Both vendors say so. Microsoft's index design guide warns that many indexes on a table slow down 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

In the test, each table started with 900,000 rows and its indexes built, then took 10,000 single-row inserts in one transaction, three runs each:

  • 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.

It isn't only five more B-tree inserts per row. New 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

Built on the 1,000,000-row table, the five indexes took 133 MB next to the table's 94 MB; the 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

is the share of rows a filter matches. An index on 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)Plan the optimizer choseLogical readsReads when forced through the index
'Cancelled', 0.1% of rowsIndex seek + key lookups3,0773,077
'Pending', 9.9% of rowsFull clustered index scan12,146303,509
'Delivered', 90% of rowsFull clustered index scan12,1462,759,128

For two of the three values, the index was dead weight: never read, still updated on every insert. Microsoft's guide compares it to a phone book sorted by family name in a city where everyone is named Smith or Jones. PostgreSQL's planner, too, uses an index only when it estimates that beats a sequential scan.

Small tables are the extreme case. Microsoft notes that their indexes might never be used but must still be updated, and PostgreSQL's docs point out that 100 rows probably fit in one page, which no index can beat.

Index queries, not columns

SQL
-- "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

The right version starts from two real query shapes. In the test, "my orders" became an index seek, and the refund queue read a of just 1,000 rows (PostgreSQL calls it a partial index). The next article in this path explains why the column order in the first index matters.

Then check which indexes earn their keep. Both engines count index reads since their statistics were last reset:

SQL
-- 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;

On the test database, the SQL Server query listed all five single-column indexes with 10,000 writes and zero reads. The PostgreSQL query follows the pg_stat_user_indexes columns in the docs and wasn't run for this article.

How to apply it in your project

  1. Start from queries, not columnsList 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.
  2. Check selectivity firstCount 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.
  3. Measure the write pathTime inserts and updates on the table before and after the change, with production-sized data, not a development table with a few hundred rows.
  4. Review usage on a scheduleAfter a full business cycle, drop indexes that are written but never read, and keep their CREATE statements 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 Status index 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.

📚 المصادر

  1. Index Architecture and Design Guide — SQL Server, Microsoft Learn
  2. Indexes: Introduction — PostgreSQL Documentation
  3. Examining Index Usage — PostgreSQL Documentation
  4. sys.dm_db_index_usage_stats — SQL Server, Microsoft Learn
  5. The Cumulative Statistics System — PostgreSQL Documentation

التعليقات (0)