Full answer
An index lookup costs a jump into the index plus a read of each matching table row. When a predicate matches most rows, those reads are scattered and add up to more work than scanning the table once in order. Planners estimate this from statistics and often choose a scan anyway.
Good candidates are selective predicates: ids, emails, foreign keys with many distinct values, and rare statuses.
For the rare 5 percent:
text
CREATE INDEX users_inactive ON users(id) WHERE NOT is_active;A low-cardinality column can still be useful as the first column of a composite index when every query filters on it, for example (tenant_id, created) in a multi-tenant table.
Measure with real data volumes; a plan on a 10-row test table says little about production.
Key points
- Selectivity decides whether an index helps
- Indexes on common values are often ignored
- Partial indexes suit rare values
- Low-cardinality columns can lead a composite index
Common mistakes
- Indexing booleans and status columns by reflex
- Judging plans on tiny test tables
Follow-ups
- How does the planner estimate selectivity?
- When would a bitmap index help (in engines that have one)?
Tips
- Explain the random-read cost