Covers selectivity and density definitions, the statistics object (header, density vector, 200-step histogram), how estimates are derived for literals, parameters and local variables, the seek-versus-scan tipping point, and when low-selectivity indexes are still useful.
Selectivity is the fraction of rows a predicate returns: OrderId = 5 is highly selective, IsActive = 1 matching 95% of rows is not. Density is 1 / distinct values for a column (or column prefix); a column with 4 statuses has density 0.25.
SQL Server keeps both in statistics: a header, a density vector for each key prefix, and a histogram of up to 200 steps on the leading column. The optimiser uses the histogram for literals and sniffed parameters and falls back to density for local variables and unknown values.
An index on a low-selectivity column is often ignored because a seek plus thousands of key lookups costs more than one scan. Trade-off: such columns are useful as part of a composite or filtered index, rarely alone.
"Selectivity is how much a predicate narrows the result: the fraction of rows it returns. Looking up one order by id is highly selective; WHERE IsActive = 1 that matches 95% of customers isn't selective at all. Density is a property of the column itself: one divided by the number of distinct values. A status column with four values has a density of 0.25, so on average each value is a quarter of the table.
SQL Server stores this in a statistics object for each index and for auto-created column statistics. It has three parts: a header with row counts and when it was last updated, a density vector for each prefix of the key, and a histogram of up to 200 steps on the leading column that records, for ranges of values, how many rows are equal to the step value and how many fall in between. When the optimiser compiles WHERE Status = 'Pending' with a literal or a sniffed parameter, it reads the histogram and might estimate 1,200 rows. With a local variable, or an OPTIMIZE FOR UNKNOWN hint, it can't see the value, so it uses density times row count, the average, which can be wildly wrong on skewed data.
Those estimates decide the plan. If an index on Status would return 40% of the table, the optimiser compares a seek plus 400,000 key lookups, each three or four random reads, against a scan of the clustered index, and the scan wins. So the mistake I see is creating an index on a low-selectivity column on its own and wondering why it's never used. For example, at [company] we [found a single-column index on IsDeleted that had zero seeks in sys.dm_db_index_usage_stats but millions of updates]. Low-selectivity columns belong in a composite index after a selective column, or in a filtered index on the rare value."
| Term | Definition | Example |
|---|---|---|
| Selectivity | Rows returned / total rows (lower fraction = more selective) | Email = @e: 1 / 2,000,000 |
| Density | 1 / distinct values | Status (4 values): 0.25 |
| Cardinality estimate | Rows the optimiser expects from an operator | Histogram says 1,200 for 'Pending' |
| Histogram step | RANGE_HI_KEY, EQ_ROWS, RANGE_ROWS, DISTINCT_RANGE_ROWS, AVG_RANGE_ROWS |
Up to 200 steps |
| Predicate | Source | Risk |
|---|---|---|
Literal WHERE Status = 'Pending' |
Histogram | Accurate if statistics are fresh |
| Parameter (sniffed) | Histogram for the first value compiled | Plan reused for very different values |
| Local variable / OPTIMIZE FOR UNKNOWN | Density vector (average) | Wrong on skewed data |
| Multiple predicates | Combined with the cardinality estimator's correlation assumptions | Under-estimates for correlated columns |
A Status column had 5 values; 'Archived' was 92% of 30 million rows and 'Pending' 0.02%. A procedure copied the parameter into a local variable, so every call estimated 6 million rows (density 0.2) and scanned. Using the parameter directly let the histogram estimate 6,000 for 'Pending': seek plus lookups, 40 ms instead of 9 seconds. A filtered index on Pending later cut it to 3 ms.
Checks whether the candidate understands how the optimiser estimates rows and why that, not index existence, decides plans.
Green flags
Red flags
DBCC SHOW_STATISTICS ('dbo.Orders', 'IX_Orders_Status_Date')
Header: Rows 30,000,000 Rows Sampled 30,000,000 Steps 5 Updated 2026-11-18 02:00
Density vector:
All density Columns
0.2 Status
3.3E-08 Status, OrderDate
Histogram (leading column only):
RANGE_HI_KEY RANGE_ROWS EQ_ROWS DISTINCT_RANGE_ROWS AVG_RANGE_ROWS
1 (Pending) 0 6,000 0 1
2 (Paid) 0 900,000 0 1
3 (Shipped) 0 1,500,000 0 1
4 (Archived) 0 27,594,000 0 1
The histogram covers only the first key column; later columns contribute only through the density vector. That is one reason why column order in composite indexes affects estimates.
EQ_ROWS.AVG_RANGE_ROWS (range rows / distinct range rows).All density * table rows.seek + lookups cost ≈ index pages + (rows × ~3 random reads)
scan cost ≈ all clustered leaf pages (sequential)
For a 30-million-row table of 400,000 pages, about 100,000 lookups already cost as much as the scan, roughly 0.3% of rows. Above that the index is ignored unless it covers the query.
Auto-update triggers after a threshold of modifications: for compatibility level 130 and later, roughly MIN(500 + 20% of rows, SQRT(1000 × rows)), so large tables update far more often than the old 20% rule. Auto-update samples by default; for skewed large tables a scheduled UPDATE STATISTICS ... WITH FULLSCAN (or PERSIST_SAMPLE_PERCENT) gives better histograms. Ascending keys (dates, identities) are a classic gap: new values above the last step were estimated as 1 row by the legacy estimator; the newer estimator assumes average density.
(CustomerId, Status): Status narrows within one customer.Status and run DBCC SHOW_STATISTICS on its index.WHERE Status = 1 with a literal, a parameter and a local variable.modification_counter and last_updated in sys.dm_db_stats_properties before and after a bulk insert.sys.dm_db_index_usage_stats to find indexes with zero seeks and many updates.Inspecting statistics, and the local-variable estimate trap in a stored procedure.
-- Statistics health for every stats object on a table
SELECT s.name AS stats_name, sp.last_updated, sp.rows, sp.rows_sampled,
sp.steps, sp.modification_counter
FROM sys.stats AS s
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
WHERE s.object_id = OBJECT_ID(N'dbo.Orders');
DBCC SHOW_STATISTICS ('dbo.Orders', 'IX_Orders_Status_Date') WITH HISTOGRAM;
-- Bad: the local variable hides the value, so the estimate is density x rows (6 million) for every status
CREATE OR ALTER PROCEDURE dbo.GetOrdersByStatus_Bad @Status tinyint
AS
BEGIN
DECLARE @s tinyint = @Status;
SELECT OrderId, OrderDate FROM dbo.Orders WHERE Status = @s;
END;
GO
-- Better: the parameter is sniffed, so the histogram gives 6,000 for Pending.
-- (Watch for sniffing issues if the same plan is reused for Archived; see parameter sniffing.)
CREATE OR ALTER PROCEDURE dbo.GetOrdersByStatus @Status tinyint
AS
BEGIN
SELECT OrderId, OrderDate FROM dbo.Orders WHERE Status = @Status;
END;
GO
-- Indexes that are maintained but never read: candidates for review (since last restart)
SELECT OBJECT_NAME(i.object_id) AS table_name, i.name AS index_name,
us.user_seeks, us.user_scans, us.user_lookups, us.user_updates
FROM sys.indexes AS i
LEFT JOIN sys.dm_db_index_usage_stats AS us
ON us.object_id = i.object_id AND us.index_id = i.index_id AND us.database_id = DB_ID()
WHERE OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1 AND i.index_id > 1
AND ISNULL(us.user_seeks + us.user_scans + us.user_lookups, 0) = 0
ORDER BY us.user_updates DESC;
From .NET, a typed parameter keeps the plan reusable and the value visible to the optimiser.
namespace Shop.Data;
using System.Data;
using Microsoft.Data.SqlClient;
public sealed record OrderRow(int OrderId, DateTime OrderDate);
public sealed class OrdersByStatus(string connectionString)
{
public async Task<List<OrderRow>> GetAsync(byte status, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
await using var cmd = new SqlCommand("dbo.GetOrdersByStatus", conn) { CommandType = CommandType.StoredProcedure };
cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.TinyInt) { Value = status });
await conn.OpenAsync(ct);
await using var reader = await cmd.ExecuteReaderAsync(ct);
var rows = new List<OrderRow>();
while (await reader.ReadAsync(ct))
rows.Add(new OrderRow(reader.GetInt32(0), reader.GetDateTime(1)));
return rows;
}
}
IsDeleted or Gender on its own. Why it is wrong: past the tipping point the optimiser scans, and the index only adds write cost. Instead: use it in a composite or filtered index.sys.dm_db_index_usage_stats right after a restart or failover. Why it is wrong: the counters reset, so a monthly-report index looks unused. Instead: collect usage over a full business cycle.Estimates, not indexes, decide plans. When a plan looks wrong, the first comparison I make is estimated versus actual rows on each operator; a 100x gap points at statistics, skew, local variables or correlated predicates long before it points at a missing index.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Composite index with the selective column first | Low-selectivity column filtered together with a selective one | Wider index | Queries filter on the low-selectivity column alone |
| Filtered index on the rare value | Skewed column, queries target the rare value with literals | Query must match the filter | Parameterised filter value |
| FULLSCAN statistics job | Large skewed tables with bad estimates | Maintenance window I/O | Small or uniform tables |
| Accept the scan | Query really returns a large share of rows | Reads the table | It runs thousands of times a minute (cover it or redesign) |
Both are B+ trees of 8 KB pages: a root, intermediate levels and a leaf level, with leaf pages linked in key order.
To find a row SQL Server seeks from root to leaf (3–4 page reads for millions of rows). If a non-clustered index lacks a column, it does a key lookup into the clustered index. The trade-off: every extra index speeds reads and slows writes.
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.
(CustomerId, OrderDate, Status) supports CustomerId = @c, CustomerId = @c AND OrderDate >= @d, but not OrderDate >= @d alone (that scans; SQL Server has no skip-scan).Trade-off: one well-ordered index can serve several queries; the wrong order serves none.
How to tell it (STAR)
**S:** At [company] our exceptions screen took about [9] seconds while every other status search was fast. **T:** I was asked to find out why one screen was slow. **A:** I compared estimated and actual rows in the plan, saw a [6 million] estimate against [4,000] actual, confirmed the histogram was accurate, and traced it to a local variable that hid the parameter from the optimiser. I removed it, added a statement-level recompile and later a filtered index for the rare statuses. **R:** The screen dropped to under [100] ms and we added a Query Store check for big estimate gaps.
Last updated 23 Nov 2026.