← Back to SQL, page 11

sql-0217 · Medium mid

Should you index a boolean column such as is_active where 95 percent of rows are true?

Usually not for the common value: a query for is_active = true would read most of the table through the index, which is slower than a plain scan. An index helps only for the rare value, and then a partial index on that value is better. Selectivity, the fraction of rows a predicate returns, decides whether an index pays off.

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