/ THE IDEA
A B-tree index stores ordered search values in branching pages, fixed-size storage blocks that direct a search toward a smaller range. A database can therefore locate a value or range without inspecting every row. But an ordinary index lookup may still need to fetch the full records from their table pages. If the matches are scattered, that follow-up work can dominate. A sequential scan reads table pages in order and tests their rows. It does more filtering but can make efficient use of sequential access and already-cached pages, meaning copies already in fast memory. The planner estimates which route costs less for this particular question, using statistics about the values and the expected number of matches.
THE FORMAL IDEA
toy index cost = 3 + 2m; toy scan cost = 100
| m is the number of qualifying rows. Three cost units represent reaching the relevant index area; two per match represent additional lookup work. | | These are invented comparison units, not measured disk operations or PostgreSQL’s own cost settings. Holding scan cost fixed isolates the effect of changing the match count. |
|
RUN THE TINY EXAMPLE
Change one thing. Predict what happens.
A search matches m = 5 rows: index cost = 3 + 2 × 5 = 13 units. The scan costs 100 units, so the index wins in this toy model. Change only the condition so m = 60 rows qualify: index cost = 3 + 120 = 123. Now the 100-unit scan wins, despite the index still existing and working correctly.
|
The threshold in this model is near 49 matches, not a universal database rule. The important change is that the index route pays extra work for each qualifying row. A lookup that was attractive for a narrow condition can become unattractive for a broad one.
/ SO WHAT?
For a slow report, compare estimated rows with actual rows using an execution report. Outdated statistics can make the planner choose using the wrong expected match count. Also inspect which columns the report needs: an index containing all required information can avoid some table fetching, changing the comparison materially.
ONE CAVEAT |
| Real choices also include bitmap scans, memory effects, physical clustering, parallel reading and index-only scans. B-tree depth and table size are not fixed constants. This is a selectivity lesson, not a benchmark or a reason to force every query to use an index. |
KEEP THIS
A lookup structure helps most when the work it avoids exceeds the per-match work it adds.
|
NEXT: Why a fan helps a hot surface lose heat
|