Sub topic 5
Sequential, index, index-only and bitmap scans
Every query plan has scan nodes at its leaves. A scan node is where PostgreSQL reads rows from a table or an index, and everything above it (joins, sorts, aggregates) works on what the scans return. This chapter assumes you can read the basic shape of a plan, including the cost=... rows=... width=... triple from the earlier chapters. It covers the four scan types you will see most often, what each one costs, and how to tell from a plan why the planner picked it.
The four scan types
| Scan node | What it reads | Output order | Typically chosen when |
|---|---|---|---|
| Seq Scan | Every page of the table, in physical order | Unordered | A large share of rows match, or the table is small |
| Index Scan | Index entries, then one heap fetch per entry | Index order | Few rows match, or the index order avoids a sort |
| Index Only Scan | Index entries, with heap visits only when needed | Index order | All needed columns are in the index and the table is well vacuumed |
| Bitmap Index Scan + Bitmap Heap Scan | Index entries into a bitmap, then heap pages in physical order | Unordered | A moderate share of rows match, or several indexes combine |
The heap is the table's own storage, as opposed to its indexes.
Sequential scan
A Seq Scan reads the whole table from start to end and tests each row against the filter.
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42;With no usable index, the plan looks like this:
Seq Scan on orders (cost=0.00..1834.00 rows=5 width=48)
Filter: (customer_id = 42)The startup cost is 0.00 because the scan can return its first row immediately. The total cost grows with the number of pages in the table, because the planner charges seq_page_cost (1.0 by default) for each page it reads.
A sequential scan is not automatically a problem. Reading pages in order is the cheapest kind of disk access. If a query needs 30% of a table, a sequential scan usually beats an index. On a table that fits in a few pages, it beats everything.
With EXPLAIN ANALYZE, a Seq Scan shows a line such as Rows Removed by Filter: 99995. A scan that reads 100,000 rows to return 5 is the pattern to look for.
Index scan
After you create an index, the planner can fetch only the matching rows:
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
ANALYZE orders;
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42;Index Scan using orders_customer_id_idx on orders (cost=0.29..8.31 rows=5 width=48)
Index Cond: (customer_id = 42)PostgreSQL walks the B-tree to find matching entries. For each entry it jumps to the heap page that holds the row. The jump is a random read, and the planner charges random_page_cost (4.0 by default) for it. That is why an index scan wins only when few rows match. At some point the cost of many random jumps exceeds the cost of reading everything in order.
An index scan has two other properties.
- It returns rows in index order. For
ORDER BY customer_id LIMIT 10, the planner can read ten index entries and stop, with no sort node at all. - The
Index Condline shows what the index itself evaluated. AFilterline under an index scan is applied to the heap row afterward, which means the index did not narrow things down for that condition.
Index-only scan
If the index contains every column the query needs, PostgreSQL may skip the heap:
EXPLAIN (ANALYZE)
SELECT customer_id
FROM orders
WHERE customer_id BETWEEN 40 AND 50;Index Only Scan using orders_customer_id_idx on orders (cost=0.29..6.10 rows=48 width=4) (actual time=0.030..0.052 rows=51 loops=1)
Index Cond: ((customer_id >= 40) AND (customer_id <= 50))
Heap Fetches: 0Heap Fetches is the line that matters. Indexes do not record whether a row is visible to your transaction, so PostgreSQL consults the table's visibility map. For pages marked all-visible, it trusts the index. For other pages it must visit the heap and check. A table with many recent updates has few all-visible pages, so an index-only scan can show thousands of heap fetches and perform no better than a plain index scan.
VACUUM maintains the visibility map. Autovacuum normally does this, but a table that is written heavily may lag behind.
You can add non-searchable payload columns to an index with INCLUDE to make more queries index-only:
CREATE INDEX orders_customer_status_idx
ON orders (customer_id) INCLUDE (status);The cost is a larger index and slower writes, so add columns only for queries that matter.
Bitmap scans
When a query matches too many rows for an index scan but too few for a sequential scan, PostgreSQL uses a bitmap scan. It is always two nodes:
Bitmap Heap Scan on orders (cost=45.20..980.10 rows=2400 width=48)
Recheck Cond: (customer_id < 100)
-> Bitmap Index Scan on orders_customer_id_idx (cost=0.00..44.60 rows=2400 width=0)
Index Cond: (customer_id < 100)The child, Bitmap Index Scan, reads the index and builds an in-memory bitmap of matching row locations. The parent, Bitmap Heap Scan, then visits the heap pages in physical order, each page once. This turns many scattered random reads into one ordered pass over only the pages that matter. The child reports width=0 because it produces a bitmap, not rows.
Three details matter when reading these nodes:
- Recheck Cond. If the bitmap gets too large for
work_mem, PostgreSQL keeps only page numbers, not exact row positions. It then rechecks the condition on every row in those pages. WithANALYZEyou will seeHeap Blocks: exact=...and, when memory runs out,lossy=.... Many lossy blocks suggestwork_memis too small for this query. - No ordering. A bitmap scan returns rows in physical order, so an
ORDER BYstill needs a sort node. - Combining indexes. With conditions on two indexed columns, the planner can build one bitmap per index and merge them with
BitmapAndorBitmapOrnodes. Only bitmap scans can do this.
How the planner chooses
The planner prices each option using its row estimate and picks the cheapest. The estimated fraction of rows that match (the selectivity) is the main input.
The boundaries are not fixed percentages. They shift with table size, correlation between index order and physical order, cache assumptions, and the cost settings. If the estimated row count is wrong, the choice is based on the wrong number. That is why scan problems often trace back to statistics, covered in a later chapter.
Experimenting safely
To see what the planner rejected, disable a scan type for your session and compare costs:
SET enable_seqscan = off;
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42;
RESET enable_seqscan;This does not forbid sequential scans. It adds a huge cost penalty, so the planner uses one only when it has no alternative. If the forced index plan has a higher cost and a slower actual time, the planner was right.
Common reasons an index is not used
- A function or expression on the column.
WHERE lower(email) = '[email protected]'cannot use a plain index onemail. Create an index onlower(email)or rewrite the condition. - A leading wildcard.
LIKE '%abc'cannot use a B-tree index for prefix matching. - Low selectivity. A condition matching most rows is faster as a sequential scan. The planner is correct to ignore the index.
- A multicolumn index used from the wrong end. An index on
(a, b)helps filters onaor onaandb. It generally does not help a filter onbalone. - Stale statistics. After a bulk load, run
ANALYZE. Otherwise the planner may think the table is nearly empty and choose a sequential scan. - A small table. On a table of a few pages, reading everything is cheaper than traversing an index.
Exercise
A query SELECT customer_id FROM orders WHERE customer_id < 500 shows an Index Only Scan with Heap Fetches: 48210 and runs no faster than an ordinary index scan. What is the likely cause, and what do you do about it?
Show answer
The visibility map has few all-visible pages, probably because the table has had many recent updates or deletes and has not been vacuumed. PostgreSQL must visit the heap to confirm row visibility, which removes the advantage of an index-only scan. Run VACUUM orders (or check why autovacuum is lagging) and run the query again. Heap Fetches should drop toward zero.
Exercise
A plan shows a Bitmap Heap Scan with Heap Blocks: exact=120 lossy=3400. What does this tell you, and which setting would you try changing?
Show answer
The bitmap did not fit in work_mem, so for most pages PostgreSQL tracked only the page and had to recheck the condition on every row in it. Raising work_mem for the session and running EXPLAIN (ANALYZE) again should shift blocks from lossy to exact and reduce recheck work.