The Runtime Theory
mediumSystemInternals#query-plans#cost-model

When Is a Sequential Scan Better Than an Index Scan?

A database prompt about selectivity, page access, planner estimates, visibility checks, and reading a real query plan.

TRT practice prompt — not a verified question from a named employer.

The Runtime Theory Team1 min read

A strong answer

A sequential scan can be better when a query needs a large fraction of a table. It reads pages in order and avoids following an index to many scattered heap locations. An index scan is attractive when a predicate is selective enough that finding a small set of rows saves more work than traversing the index and fetching table pages.

The right choice depends on row distribution, table and index size, cache state, storage characteristics, row visibility, and the query's required columns. An index-only scan can avoid some heap visits when its requirements are met, but it is not automatic for every query.

The optimizer uses statistics and a cost model to estimate alternatives. I would inspect EXPLAIN, compare estimated rows with actual rows using EXPLAIN ANALYZE, and verify the workload before adding an index. Planner cost units are not wall-clock milliseconds, and ANALYZE executes the statement.

Follow-up direction

Use the PostgreSQL plan guide to walk through a concrete scan node and identify where its input rows come from.

This answer walks

Practice follow-ups

  1. 01Why can stale statistics produce a poor plan?
  2. 02What extra work can an ordinary index scan perform after locating a key?
  3. 03How do you compare estimated and actual row counts?

One dispatch a week

The trace behind each question, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.

Not started

Sign in to save your learning progress.

Sign in to save