Mohammad Zhalehpour

Note

When a SQL Server index helps

The subject of this note is an index on a booking table, where both reads and writes are frequent. An index may make search faster and new rows slower. The execution plan should be read before one is added.

A smarter optimizer in newer SQL Server releases does not change the habit: name the query that is actually slow, read its actual plan, make one change, and measure both the read and the write.

Read the sign in the plan

What the plan showsWhat to do with it
A function on the column in the predicateThe seek is gone. The predicate has to be on the column itself.
An implicit conversionComparing nvarchar to varchar, or a date to a string, often does the same damage.
A key lookupThe index found the row and went back to the table for the other columns. If that lookup is frequent, cover the output with INCLUDE.
Many indexes on a hot tableEvery insert and update maintains several trees and widens the log.

INCLUDE columns make the index wide. Covering ten columns “just in case” spends the write budget on a case that has not happened. Cover the columns this query returns, not every column you might want later.

Filtered indexes, used properly

For open rows, such as holds that are not settled yet, a filtered index on a stable status is useful. The filter predicate has to be deterministic. ExpiresAt > GETDATE() is rejected in an index definition, and it should be: an index cannot recompute membership every second.

Releasing an expired hold is not the index’s job. It is an explicit update. The index only makes reading that status cheap. The flow around that update is in the booking-path note.

A good plan for a rare value

If a query is compiled for a rare value and then reused for a common one, the plan can be wrong for both. That is parameter sniffing. The remedy is not a hint on every query. Keep rare administrative queries separate. For the operational query, refresh statistics after a large data change and keep the parameter shape stable. OPTION (RECOMPILE) belongs on an infrequent report, not on the booking path.

Columnstore is for analysis, not for recording capacity and payment. Do not mix those two workloads in one index.

The habit that replaces a ready-made script

  1. Name the query after the incident, not after the table.
  2. Read the actual plan, not only the estimated one, when production-like data is available.
  3. Add or change one index.
  4. Compare read time, extra writes, and log growth with the previous shape.
  5. If the read improved and the booking write got worse, do not quietly drop the index and forget it. Write the decision next to the index.

Rebuilding every index every week is not maintenance. If you have not measured page splits, the rebuild is just extra load. A good index is one that makes a named query cheap, with someone who has accepted the write cost.

Was this note useful?