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

📚 Interview question

What are selectivity and density in SQL Server? How do they relate to statistics and histograms, how does the optimiser use them to estimate rows, and why does it often ignore an index on a low-selectivity column?

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.

Mid-Level Theory Intermediate cardinality-estimation indexes query-optimiser selectivity sql-server statistics

🎯 Key points

  • Selectivity = fraction of rows a predicate returns; high selectivity = few rows
  • Density (All density) = 1 / distinct values per key prefix; it assumes values are evenly spread
  • Statistics = header, density vector and a histogram of up to 200 steps on the leading column
  • Literals and sniffed parameters use the histogram; local variables and unknown values use density x rows
  • Skewed data: one value can be 0.02% of rows and another 92%; only the histogram captures it
  • Low-selectivity index plus key lookups costs more than a scan past the tipping point
  • Stale or sampled statistics distort estimates: check sys.dm_db_stats_properties and refresh key tables
  • Composite and filtered indexes make low-selectivity columns useful

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

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


Terms

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

Where the estimate comes from

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands how the optimiser estimates rows and why that, not index existence, decides plans.

Green flags

  • Defines selectivity and density correctly
  • Describes the histogram (200 steps, leading column) and density vector
  • Knows local variables fall back to density
  • Explains the tipping point and when low-selectivity columns still help

Red flags

  • "The optimiser always uses an index if there is one"
  • Cannot say where estimates come from
  • Indexes boolean columns on their own

📚 Learn in depth

1. The statistics object

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.

2. How estimates are computed

  • Equality on a step value: EQ_ROWS.
  • Equality between steps: AVG_RANGE_ROWS (range rows / distinct range rows).
  • Range predicates: sum of steps, interpolated at the edges.
  • Unknown value: All density * table rows.
  • Multiple predicates: the default cardinality estimator (since SQL Server 2014) uses exponential backoff, assuming partial correlation, rather than multiplying selectivities outright.

3. The tipping point

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.

4. Keeping statistics fresh

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.

5. When low selectivity is fine

  • Composite index (CustomerId, Status): Status narrows within one customer.
  • Filtered index on the rare value.
  • Covering index: no lookups, so even returning 30% of rows from a narrow index is cheaper than scanning a wide table.

Try it yourself

  1. Build a 10-million-row table with a skewed Status and run DBCC SHOW_STATISTICS on its index.
  2. Compare estimated rows for WHERE Status = 1 with a literal, a parameter and a local variable.
  3. Find the tipping point: query growing ranges of an indexed date column until the plan flips to a scan.
  4. Check modification_counter and last_updated in sys.dm_db_stats_properties before and after a bulk insert.
  5. Use sys.dm_db_index_usage_stats to find indexes with zero seeks and many updates.

💻 Code

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

⚠ Common mistakes

  • Mistake: Indexing a low-selectivity column such as 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.
  • Mistake: Confusing selectivity and density directions. Why it is wrong: low density (many distinct values) means high selectivity; mixing them up leads to wrong conclusions. Instead: density = 1/distinct values; selectivity = fraction returned.
  • Mistake: Copying parameters into local variables "to avoid sniffing" by habit. Why it is wrong: the estimate becomes the average from density, which is wrong for every skewed value. Instead: fix sniffing deliberately (RECOMPILE, PSP, OPTIMIZE FOR).
  • Mistake: Assuming the histogram covers every column of a composite index. Why it is wrong: only the leading column has a histogram. Instead: create column statistics or reorder columns if estimates on later columns matter.
  • Mistake: Relying only on auto-update for huge skewed tables. Why it is wrong: sampled statistics miss rare values and updates lag behind ascending keys. Instead: scheduled FULLSCAN or persisted sample percent for key tables.
  • Mistake: Reading 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.

🏛 Senior insight: trade-offs

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)

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the cost of key lookups. Why: Checks the key lookup mechanics behind the tipping point.
    How to answer

    Both are B+ trees of 8 KB pages: a root, intermediate levels and a leaf level, with leaf pages linked in key order.

    • A clustered index is the table: its leaf pages hold the full rows, sorted by the clustered key. There is only one per table.
    • A table with no clustered index is a heap; rows sit wherever there is space and are found by a RID (file, page, slot).
    • A non-clustered index is a separate, sorted copy of some columns. Its leaf holds the index key plus a row locator: the clustered key, or the RID on a heap.

    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.

  2. When: Candidate suggests a composite index. Why: Checks how to combine a low-selectivity column with a selective one.
    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.

🛠 Real-world problems: how you handle them

Report search slow for one status after a defensive local variable
Situation
A [logistics] back office searched [30 million] shipments by status through a stored procedure on SQL Server 2022. Most searches targeted rare statuses such as 'Exception'.
Signals
Users reported the 'Exceptions' screen taking [9] seconds; Application Insights showed the procedure's dependency p95 at [8.7] s while other screens were fast; Query Store showed one plan with a clustered index scan for every status.
Investigation
The actual plan estimated [6 million] rows for every call against [4,000] actual for 'Exception'. `DBCC SHOW_STATISTICS` showed a good histogram, so statistics were fine. The procedure copied `@Status` into a local variable, a change made [months earlier] to 'fix parameter sniffing', which forced the density-based average estimate.
Resolution
Immediate: removed the local variable and added `OPTION (RECOMPILE)` on that statement (low execution count, so compile cost was acceptable), giving histogram estimates per call. Long-term: added a filtered index on the rare statuses so the common screen did a covering seek.
Prevention
A Query Store report on queries with large estimated-versus-actual gaps; a code-review rule against local-variable copies of parameters without a recorded reason; a note in the team's SQL guidelines on sniffing fixes.

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.

↩ Usually asked after

More in Indexes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me