Sub topic 5
Selectivity: when an index helps and when it does not
This chapter assumes you can read basic SQL, know what a B-tree index is, and have seen an EXPLAIN plan. The examples use PostgreSQL syntax and the orders table from earlier in this tutorial.
What selectivity means
Selectivity is the fraction of a table's rows that a predicate matches. A predicate matching 10 rows out of 1,000,000 has a selectivity of 0.00001. It is highly selective. A predicate matching 400,000 rows has a selectivity of 0.4 and is weakly selective.
Cardinality is a related word. The cardinality of a column is the number of distinct values it holds. A primary key has the highest possible cardinality, because every row has a different value. A boolean column has a cardinality of 2.
The two ideas are linked but not identical. A high-cardinality column usually gives selective predicates, but only when values are spread evenly. A column with a million distinct values can still have one value that covers half the table.
Why selectivity decides whether an index helps
An index lookup does not return rows. It returns pointers to rows. For each pointer, the database then visits the table page that holds the row. These visits are usually random reads, scattered across the table.
A sequential scan reads every page in order. Sequential reads are cheap per page, and the operating system and storage can prefetch them.
So the choice is between two costs:
- An index scan costs a few page reads to descend the tree, plus roughly one random table-page read per matching row.
- A sequential scan costs one cheap read per page in the whole table, whatever the predicate.
When few rows match, the index wins easily. When many rows match, the random reads add up until they cost more than reading the whole table in order. The crossover point depends on row width, caching, and storage speed. It is often a small percentage of the table, not half of it.
Low-cardinality columns
Consider the status column in orders. Suppose it holds only open, shipped, cancelled, and returned. An index on status alone is rarely useful for a query like this:
SELECT * FROM orders WHERE status = 'shipped';If 90% of orders are shipped, the planner will choose a sequential scan. The index is not used, but it still costs space and slows every write.
Skew changes the answer. If only 0.1% of orders are open, the same index is very useful for WHERE status = 'open'. The planner can use the index for the rare value and ignore it for the common one. Section "Skewed data" below covers how it knows the difference.
How the planner estimates selectivity
The planner does not count matching rows before running your query. It estimates them from statistics stored in the system catalogs. In PostgreSQL, the ANALYZE command (also run by autovacuum) samples each table and records, per column:
- The fraction of NULLs.
- The number of distinct values (
n_distinct). - A list of the most common values and their frequencies.
- A histogram that divides the remaining values into buckets of equal population.
You can inspect these in the pg_stats view:
SELECT attname, null_frac, n_distinct, most_common_vals, most_common_freqs
FROM pg_stats
WHERE tablename = 'orders' AND attname = 'status';For status = 'shipped', the planner looks up shipped in the most-common-values list and reads its frequency. For a value not in the list, it spreads the leftover probability over the remaining distinct values. For range predicates, it uses the histogram.
Multiplying the row count by the estimated fraction gives the expected number of matching rows. The planner compares the cost of each access path using that number and picks the cheapest.
Seeing the choice in EXPLAIN
You can watch the plan change as the predicate changes. Assume the skewed status distribution above and an index on status:
CREATE INDEX orders_status_idx ON orders (status);
ANALYZE orders;
EXPLAIN SELECT * FROM orders WHERE status = 'open';
EXPLAIN SELECT * FROM orders WHERE status = 'shipped';A typical result is an Index Scan or Bitmap Heap Scan on orders_status_idx for the first query, and a Seq Scan on orders for the second. The exact node names and costs depend on your data.
The bitmap scan sits between the two extremes. The database reads the index first and builds a bitmap of the table pages it needs. It then reads those pages in physical order, once each. This removes the repeated random reads that make a plain index scan expensive when a moderate fraction of rows match.
Skewed data and the limits of statistics
The statistics are a summary, so the estimates can be wrong. Common causes:
- Stale statistics. After a bulk load or a large delete, the stored numbers no longer describe the table. Run
ANALYZEon the table to refresh them. - Correlated columns. The planner assumes columns are independent. If
city = 'Paris'andcountry = 'France'are almost the same condition, multiplying their selectivities underestimates the rows. PostgreSQL offersCREATE STATISTICSto record dependencies between columns. - Values outside the sample. A rare value may be missing from the most-common list, and its estimate is then a guess based on the average.
- Parameterized queries. With a generic plan, the planner may not know the actual parameter value, so it estimates for an average value. A query for a rare value and a query for a common value may then share one plan.
When you see a large gap between the estimated and actual row counts in EXPLAIN ANALYZE, suspect one of these causes before you suspect the index.
Selectivity of combined predicates
Selectivity also explains why a composite index can help when two single-column indexes do not. Suppose status = 'shipped' matches 90% of rows and customer_id = 42 matches 0.01%. The second predicate alone is selective, so an index on customer_id is enough. Adding status as a second index column would not narrow the search much.
The reverse case is where combination matters. If status = 'open' matches 5% and created_at in the last day matches 3%, neither is very selective alone. Together they might match 0.2%, and a composite or partial index on both can serve that query well.
Exercise
A table has 5,000,000 rows. The column is_active is boolean, and 97% of rows have is_active = true. You run SELECT * FROM users WHERE is_active = true and the plan shows a sequential scan even though an index on is_active exists. Why is that choice reasonable? Which query on the same column would likely use the index?
Show answer
The predicate matches about 97% of the table. Using the index would add one random table-page read for each of roughly 4.85 million rows, on top of reading the index, which costs more than reading the table once in order. The query WHERE is_active = false matches about 3% of rows and is much more likely to use the index, because it is far more selective. A partial index on is_active = false rows would serve it with less storage.
Exercise
After loading 2 million new rows into orders in one batch, a query that used to run an index scan now runs a sequential scan, and EXPLAIN ANALYZE shows an estimated row count of 20 against an actual count of 300,000. What is the most likely cause, and what is the first step to fix it?
Show answer
The statistics are stale, so the planner is estimating from the table's old contents. Run ANALYZE orders; to refresh them, then compare the plan again. If the estimate is still far from the actual count, check for correlated columns or skewed values that need extended statistics.