Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Systems · Databases

The Cheapest Way to Run It.

You write what you want — SELECT … WHERE city = 'NYC' AND age > 30 — and the database decides how to get it. That decision is made by the query planner, and it’s the single biggest reason two queries that look identical can differ by a thousandfold in speed. The planner is cost-based: it enumerates the ways it could execute the query — read every row (a sequential scan), jump straight to matching rows through an index scan, or combine two indexes with a bitmap AND — estimates a cost for each using statistics about your data, and runs the cheapest. The counter-intuitive part, the thing that trips up most engineers: an index is not always faster. If a condition matches most of the table, chasing an index means thousands of scattered random reads, and a plain sequential scan wins. The deciding factor is selectivity — what fraction of rows a condition keeps. Change the selectivity of each predicate, toggle the indexes, and watch the planner flip its choice, with the cost of every candidate laid bare.

cost-based · seq scan vs index scan vs bitmap AND · selectivity decides · an index isn’t always a win
sequential scan

Read every row in the table in order. Cheap per row, but you touch all of them.

index scan

Use an index to jump to matching rows. Fast when few rows match; costly random reads when many do.

selectivity

The fraction of rows a condition keeps. Few rows match (a selective condition): an index wins. Most rows match: a scan wins.

bitmap AND

Read two indexes into bitmaps, intersect them, then fetch only the rows in both — great when each index is selective.

planner.js — estimate every plan, run the cheapest
Ready
The planner costs every way to run WHERE city='NYC' AND age>30 on 100,000 rows and picks the cheapest. Change how selective each predicate is, and toggle which indexes exist. Watch the winning plan flip.
—
chosen plan
—
est. cost
—
rows returned

How it works

A planner turns a declarative query into a physical plan by doing something almost mechanical: it enumerates candidate plans and prices each one, then keeps the minimum. The prices come from a cost model over table statistics — chiefly the row count and the selectivity of each predicate (estimated from histograms the database keeps on each column). The key asymmetry the model captures is that a sequential scan reads pages in order (cheap per row, but it reads them all), whereas an index scan does a random heap fetch for each match (expensive per row, but only for matching rows). So index cost grows with the number of matches while scan cost is fixed — and they cross over at some fraction of the table (25% in this lab’s per-row model; real planners price pages, and with PostgreSQL’s random_page_cost of 4.0 an index over rows scattered across the table stops winning far lower, around 0.5% at 50 rows to a page). Below the crossover, the index wins; above it, the scan wins, which is why an index on a column that matches most rows is dead weight. When a query has two selective predicates each with an index, a third option appears: read both indexes into bitmaps, AND them, and fetch only the rows in the intersection — cheaper than either index alone. The planner doesn’t know your intent; it just prices these shapes against the current statistics and picks the cheapest, which is why keeping statistics fresh (running ANALYZE) matters so much — stale stats mean mispriced plans and sudden slowdowns.

1

Estimate selectivity

From column statistics, the planner estimates what fraction of rows each predicate keeps — the single most important input. The city match might keep 2% of rows; age over 30 might keep 60%.

2

Price each candidate plan

It costs a sequential scan (read all rows), an index scan per available index (random fetch of matching rows), and — if two selective indexes exist — a bitmap AND. Index cost grows with the number of matches.

3

Pick the minimum

The cheapest candidate wins. A selective predicate with an index gives a cheap index scan; a broad predicate makes its index worthless and a sequential scan wins instead.

✓

Why it flips

Change selectivity and the winner flips: two selective indexes make a bitmap AND cheapest; a non-selective predicate sends the planner back to a full scan. Stale statistics mispriced this — which is why ANALYZE matters.

Decision
minimum estimated cost
Key input
selectivity (row fraction)
Seq scan
fixed cost, reads all
Index scan
cost grows with matches

The code

# Cost-based planning (simplified), 100k-row table N = 100_000 sel_city, sel_age = 0.02, 0.60 # from column statistics seq_cost = N # read every row, in order idx_city = sel_city * N * 4 # random heap fetch per match idx_age = sel_age * N * 4 bitmap_and = 0.5*(sel_city+sel_age)*N + 2*(sel_city*sel_age)*N plans = {'Seq Scan': seq_cost} if has_index('city'): plans['Index Scan (city)'] = idx_city if has_index('age'): plans['Index Scan (age)'] = idx_age if has_index('city') and has_index('age'): plans['Bitmap AND'] = bitmap_and chosen = min(plans, key=plans.get) # run the cheapest

The picture: where the index stops paying

est. cost 100k 200k 0% 25% 50% selectivity: fraction of rows the predicate keeps seq scan = N = 100k index scan = 4 × s × N bitmap AND, other at 5% crossover: 4 × s × N = N, s = 25% index cheaper seq scan cheaper
The lab’s whole decision on one chart. A sequential scan costs the same however many rows match. An index scan charges 4 per matching row, a random fetch at four times the price of an in-order read, so it crosses the scan at exactly 25%. The bitmap AND line is why two modest indexes can beat both. It reads index entries cheaply and pays per row only for the rows in both sets.

Worked example: pricing every plan, button by button

The candidates and costs the lab computes for WHERE city = 'NYC' AND age > 30 on 100,000 rows. Each row is one setting of the two buttons. A dash means the plan is not available.

city / age matchSeqIndex (city)Index (age)Bitmap ANDWinner, rows out
2% / 60% (default)100k8k240k33.4kIndex (city), 1,200
10% / 5%100k40k20k8.5kBitmap AND, 500
30% / 30%100k120k120k48kBitmap AND, 9,000
60% / 5%100k240k20k38.5kIndex (age), 3,000
30% / 90%100k120k360k114kSeq Scan, 27,000
2% / 60%, idx_city dropped100k—240k—Seq Scan, 1,200

Row 3 is the surprise. Neither index on its own beats the scan, since 120k is more than 100k, yet together they cost 48k, because the bitmap charges 0.5 for each of the 60,000 index entries it reads (30k) and 2 for each of the 9,000 rows in both sets (18k). Row 6 is the default query after someone drops idx_city: the same 1,200 rows now cost 100k instead of 8k, which is 12.5 times more. The age index cannot help, because at 60% it is far past the crossover. One more thing to notice: “rows out” is s1 × s2 × N. The lab assumes the two predicates are independent, which is also what real planners assume by default, and the first mistake below is about exactly that.

Cost and trade-offs of each access path

N rows, m matching rows. Space includes what the structure costs you outside the query.

CaseTimeSpaceWhy
Sequential scanO(N) page reads, in orderNone beyond the tableThe cost is fixed. It wins once the matches are a large enough fraction of the table.
B-tree index scanO(log N + m), with up to m random heap fetchesO(N) index on disk, plus work on every writeCheap for small m. Each match can be a fetch from a different page.
Bitmap ANDO(m₁ + m₂) index entries, then heap pages in physical orderA bitmap per index, in memoryTurns random fetches into one ordered pass. In PostgreSQL a bitmap that outgrows work_mem goes lossy and rechecks whole pages.
Index-only scanO(log N + m), no heap fetchA wider index that covers every column the query readsSkips the table entirely, at the price of a bigger index to maintain.
Each extra indexFaster reads for the queries it servesDisk, plus slower inserts and updatesEvery write updates every index on the table. An index the planner never picks costs you on every write and buys nothing.

The lab prices rows. Real planners price pages, and that moves the crossover a long way. PostgreSQL’s defaults are seq_page_cost = 1.0 and random_page_cost = 4.0. Say the 100,000 rows sit 50 to a page. Then the scan reads 2,000 pages, costing 2,000. An index scan over rows scattered across the table needs about one random page per match, at 4 each. So the index stops winning near 500 rows, which is 0.5% of the table, not 25%. When the table is physically ordered by the indexed column, matches share pages and the crossover moves back up. That is why the planner also tracks the correlation between a column and the table’s physical order.

Common mistakes with query plans

  • Correlated predicates estimated as independent

    city = 'NYC' AND state = 'NY' keeps every NYC row, but multiplying the two selectivities predicts far fewer. An underestimate like that picks nested loops and index scans sized for a handful of rows. PostgreSQL’s CREATE STATISTICS can record dependencies between columns so the estimate stops multiplying.

  • Hiding the column inside a function

    WHERE lower(email) = … or WHERE date(created_at) = … cannot use a plain index on that column. Index the expression itself, or rewrite the condition as a range on the bare column: created_at >= day AND created_at < day + 1.

  • Mixing up “low selectivity” and “highly selective”

    Selectivity is a fraction, so a low number (2%) means a highly selective predicate, the kind an index helps. People also say a “low-selectivity column” to mean one that matches most rows. The two phrasings run in opposite directions. Say the percentage instead.

  • Testing plans on a dev-sized table

    At 1,000 rows the whole table is a few pages, so a sequential scan wins and the index looks useless. In production the same query may be planned differently, either way. Check plans against production-sized data and fresh statistics.

  • Indexing every column in the WHERE clause, separately

    Separate single-column indexes depend on a bitmap AND to combine, and the planner will skip any of them that is past its crossover. A composite index ordered to match the query, equality columns first and then the range, usually serves a hot query better and costs one index on writes, not several.

Where this shows up in production

  • PostgreSQL

    The lab’s plans are real node names in EXPLAIN: Seq Scan, Index Scan, and Bitmap Index Scan feeding a BitmapAnd and a Bitmap Heap Scan. On SSDs, teams often lower random_page_cost toward seq_page_cost, which tells the planner random reads are cheaper and moves the crossover toward the index.

  • MySQL

    InnoDB’s index merge can intersect two indexes, shown as Using intersect(…) in EXPLAIN. It is the same idea as the bitmap AND. More often it picks a single index or a composite one, so the composite-index advice above matters even more there.

  • The query that got slow by itself

    No code changed, the data grew, and the statistics went stale. The planner now prices a plan for a table that no longer exists. Autovacuum’s auto-analyze usually catches up, but a bulk load followed straight away by queries can run before it does. Run ANALYZE after big loads.

  • Interview angle

    “Why isn’t my index being used?” The strong answer is the lab in four steps: estimate selectivity, compare random fetches against an ordered scan, check whether the estimate is wrong (EXPLAIN ANALYZE, estimated against actual rows), then fix the cause, whether that is statistics, a function on the column, or the wrong index.

Quick check

1. A predicate matches 70% of the table. Even with an index on that column, why does the planner usually pick a sequential scan?

2. What is the single most important input to the planner’s cost estimates?

3. When does a bitmap AND of two indexes become the cheapest plan?

FAQ

What is a SQL query planner?

The part of a database that decides how to execute a SQL query. You write declarative SQL saying what you want; the planner figures out the physical steps — which indexes to use, join order, scan vs seek — by enumerating candidate plans, estimating a cost for each from statistics, and running the cheapest. It’s the main reason two logically identical queries can differ enormously in speed.

Why does the database sometimes ignore my index?

Because the planner estimated using it would be slower. An index scan uses random I/O and its cost grows with the number of matches, so if your condition matches a large fraction of rows (a non-selective predicate), a sequential scan (ordered, one touch per row) wins. It’s priced and rejected, not ignored. Other real causes: stale statistics (run ANALYZE), a function/type mismatch on the indexed column, or a query returning most of the table.

What is selectivity in a query plan?

The fraction of rows a predicate keeps. A highly selective predicate (like a unique-ID equality) keeps very few rows and favours an index; a non-selective one (a boolean true for most rows) keeps most rows and favours a sequential scan. The planner estimates it from column statistics (histograms, distinct-value counts) and it’s the dominant factor in scan-vs-index choices. Bad selectivity estimates are the usual root cause of a suddenly slow query.

How do I read a query plan with EXPLAIN?

EXPLAIN shows the chosen plan tree — each node’s operation (Seq Scan, Index Scan, Bitmap Heap Scan, the join types) with estimated cost and rows. EXPLAIN ANALYZE runs it and adds real timing and real row counts. The key habit: compare estimated vs actual rows — a big mismatch means the statistics are wrong, which is usually why the plan is bad. Then fix the cause: ANALYZE to refresh stats, add/adjust an index, or rewrite the predicate so an index can be used.

Keep going

Finished this one? 0 / 61 Labs done
NextThe Eviction Race: LRU vs LFU Next on the “Storage, caching and backpressure” ladder · rung 3 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Labs