Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

How does a cost-based optimizer choose between a sequential scan and an index scan, and what role do table statistics play?

A cost-based optimizer builds candidate plans, such as a sequential scan and an index scan, estimates the cost of each from table statistics and cost parameters, and picks the cheapest. Statistics such as row counts, most common values, histograms and n_distinct tell it how many rows a predicate will match; when that is a large fraction of the table, one sequential pass is cheaper than many random index lookups. Cost parameters like random_page_cost weight the two kinds of I/O, and stale statistics after big loads make the estimates, and so the choice, wrong.

Why this question is asked

Developers are often surprised that PostgreSQL ignores an index they just created, or uses one for some values and not for others. This is not a bug; it is the cost-based optimizer doing its job. Interviewers ask this question to check that we understand selectivity and why an index is not always faster. In this answer, we will recap what the optimizer does, see how statistics give it row estimates, compare the cost of a sequential scan and an index scan with real numbers, look at the cost parameters, and finish with what happens when statistics go stale.

1A Quick Recap of the Cost-Based Optimizer

The optimizer, also called the planner, is the part of the database that decides how to run a query. A cost-based optimizer does this by estimating the cost, an approximate amount of work, for each way it could run the query, and choosing the lowest. For a simple filter on one table the main choices are a sequential scan, which reads every page of the table in order, and an index scan, which uses an index to find matching rows and then fetches each one from the table.

Everything depends on one estimate: how many rows the WHERE clause will match. The fraction of rows matched is called selectivity. A predicate that matches 0.01% of rows is highly selective; one that matches 60% is not.

2Where the Row Estimates Come From

The optimizer cannot count matching rows without running the query, so it uses statistics that ANALYZE gathered earlier from a sample of the table. In PostgreSQL we can read them in the pg_stats view.

SQL
SELECT attname, n_distinct, most_common_vals, most_common_freqs, histogram_bounds
FROM pg_stats WHERE tablename = 'orders' AND attname = 'status';
-- status | 5 | {DONE,NEW,FAILED,...} | {0.92,0.05,0.002,...} | null
SELECT reltuples FROM pg_class WHERE relname = 'orders';
-- 10000000

The table has about 10 million rows (reltuples). most_common_vals lists the most frequent values, and most_common_freqs their fractions. n_distinct is the estimated number of different values, and histogram_bounds splits the remaining values into buckets of equal population, which is how the optimizer estimates ranges such as created_at > '2026-01-01'. So for status = 'FAILED' the optimizer estimates 0.002 x 10,000,000 = 20,000 rows, and for status = 'DONE' it estimates 9.2 million rows.

3Why a Sequential Scan Can Beat an Index

A sequential scan reads pages one after another, which storage handles efficiently because it can read ahead. An index scan jumps around: for each matching index entry, it fetches the table page holding that row, and those pages are scattered. The optimizer models this with two parameters: seq_page_cost (1.0 by default) for a page read in sequence, and random_page_cost (4.0 by default) for a page read at a random position.

Suppose the table has 200,000 pages. A sequential scan costs about 200,000 page units plus a small CPU cost per row, regardless of the predicate. For status = 'FAILED', an index scan touches perhaps 20,000 scattered pages at 4.0 each, about 80,000 units, so the index wins. For status = 'DONE', the index scan would visit nearly every page, many of them more than once, at four times the price, so the sequential scan wins easily. The crossover is often at a few percent of the table, depending on how rows are laid out.

Java
EXPLAIN SELECT * FROM orders WHERE status = 'FAILED';
-- Bitmap Heap Scan on orders (cost=380.00..61000.00 rows=20000 width=60)
-- -> Bitmap Index Scan on orders_status_idx (cost=0.00..375.00 rows=20000 width=0)
EXPLAIN SELECT * FROM orders WHERE status = 'DONE';
-- Seq Scan on orders (cost=0.00..325000.00 rows=9200000 width=60)
How selectivity drives the choice (10M rows, 200,000 pages)
PredicateEstimated rowsLikely planWhy
id = 1231Index Scanone lookup, a few pages
status = 'FAILED'20,000 (0.2%)Bitmap or Index Scanfar fewer pages than the table
created_at in last 30 days500,000 (5%)Bitmap Heap Scannear the crossover; layout matters
status = 'DONE'9,200,000 (92%)Seq Scanreading everything once is cheapest

Notice the bitmap scan in the first plan. It is a middle path: PostgreSQL first collects all matching row locations from the index, sorts them by page, and then reads the pages in physical order, so each page is read once. The optimizer chooses among sequential, index and bitmap scans purely by estimated cost.

4Tuning the Cost Parameters

The default random_page_cost of 4.0 reflects spinning disks, where a random read is much slower than a sequential one. On SSDs and most cloud storage the difference is much smaller, so random_page_cost is often lowered towards 1.1. That makes index scans look cheaper and moves the crossover point. effective_cache_size, an estimate of how much memory is available for caching, also matters: a higher value tells the optimizer that repeated index lookups will often hit cached pages.

These are hints about the hardware, not knobs to fix individual queries. Changing them affects every plan, so we change them once, after measuring, rather than to rescue one slow query.

5When Statistics Go Stale

The whole process rests on statistics, and statistics are a snapshot. If a nightly job loads 5 million new orders with status 'NEW', the stored frequencies still say NEW is 5%, and new dates beyond the histogram's last bucket are poorly represented. The optimizer then estimates wrongly and may choose an index scan for what is now a huge result, or a sequential scan for a now tiny one.

ANALYZE refreshes the statistics, and autovacuum runs it automatically once enough rows have changed. After bulk loads it is good practice to run ANALYZE explicitly, because the automatic run may come much later.

6Follow-up questions

What does the correlation column in pg_stats tell you?

It measures how closely the physical order of rows on disk follows the sorted order of the column, from -1 to 1. A value near 1 or -1, typical for an ever-increasing created_at column, means that rows with neighbouring values sit on the same or adjacent pages, so an index range scan reads pages almost sequentially and is cheap. A value near 0 means matching rows are scattered, so each one may need a separate random page read. The optimizer uses correlation to estimate index scan cost, which is why an index on created_at may be used for a 10% range while an index on a random column is not.

Why does the optimizer sometimes ignore a brand-new index?

Either because, by its estimates, the predicate matches too many rows for the index to be cheaper, or because the statistics do not reflect the data yet. Running ANALYZE on the table and comparing estimated and actual rows with EXPLAIN ANALYZE shows which one it is. It can also be that the query is not sargable, for example a function on the column, so the index cannot be used at all.

Is MySQL's optimizer cost-based too?

Yes. InnoDB's optimizer also estimates costs, using index statistics and, for ranges on indexed columns, index dives that sample the index directly. Since MySQL 8.0 it can also use histograms on columns, created with ANALYZE TABLE ... UPDATE HISTOGRAM. The same principle applies: an index is used only when the estimated matching fraction makes it cheaper.

7Conclusion

In this answer, we saw that a cost-based optimizer estimates the cost of each candidate plan and picks the cheapest. Its row estimates come from statistics in pg_stats, such as row counts, most common values and frequencies, histograms and n_distinct. When a predicate matches a large fraction of rows, one sequential pass beats many random index lookups, a balance weighted by seq_page_cost and random_page_cost, which is often lowered towards 1.1 on SSDs. Finally, stale statistics after large loads give wrong estimates and wrong plans, which ANALYZE or autovacuum's auto-analyze fixes.

What to say in the interviewAbout 80 seconds aloud

Open with

The optimizer builds candidate plans, for a simple filter mainly a sequential scan, an index scan or a bitmap scan, estimates the cost of each and takes the cheapest.

Then, if they want more

The key input is how many rows the predicate matches. It gets that from statistics ANALYZE collected: the row count of the table, and per column the most common values with their frequencies, a histogram for the other values, and n_distinct, all visible in pg_stats. So if FAILED appears in 0.2% of 10 million rows, it expects 20,000 rows.

Then it compares costs. A sequential scan reads every page once in order, which is cheap per page. An index scan jumps to scattered pages, which the planner charges at random_page_cost, 4 by default against 1 for sequential pages.

For 0.2% of the table the index wins; for 90% the sequential scan wins because it would touch almost every page anyway. On SSDs we often lower random_page_cost to around 1.1, which makes index scans more attractive. The weak point is statistics. After a big load they describe the old data, the estimates are wrong, and so is the plan. Running ANALYZE after large loads, or letting autovacuum's auto-analyze catch up, fixes that.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8.0
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does a cost-based optimizer choose between a sequential scan and an index scan, and...": https://scrivio-interview-library.netlify.app/databases/query-optimization/c32469cb91/