Sub topic 2
How PostgreSQL scans: sequential, index and bitmap
This chapter assumes you can run EXPLAIN and read a simple plan. It also assumes you know a B-tree index maps key values to row locations. The chapter covers the three ways PostgreSQL reads rows from an ordinary table. Index-only scans build on these three and get their own chapters.
The examples use the orders table created earlier in this tutorial: one million rows, a primary key on id, and an index orders_customer_idx on customer_id. Plan shapes and timings depend on your hardware, settings and statistics, so treat the plans shown here as typical, not guaranteed.
The two costs that drive every choice
The planner picks the scan method with the lowest estimated cost. Two things dominate that estimate:
- Pages read. PostgreSQL reads storage in 8 kB pages. Cost is mostly about how many pages a query touches.
- Access pattern. Reading pages in physical order (sequential I/O) is cheaper than jumping between them (random I/O). The settings
seq_page_cost(default 1.0) andrandom_page_cost(default 4.0) encode this. On SSDs many people lowerrandom_page_costto around 1.1, which makes index scans look cheaper.
The third input is selectivity, the fraction of the table's rows that a WHERE condition matches. The planner estimates it from statistics collected by ANALYZE. Low selectivity (many rows match) favors reading the whole table. High selectivity (few rows match) favors an index.
Sequential scan
A Seq Scan reads every page of the table heap from first to last and checks each row against the filter. It never touches an index.
EXPLAIN
SELECT * FROM orders WHERE status = 'paid';Gather
Workers Planned: 2
-> Parallel Seq Scan on orders
Filter: (status = 'paid'::text)About a quarter of the rows have status paid. An index would send the executor to a quarter of all rows scattered across nearly every page, so reading the heap straight through is cheaper. A Seq Scan is not a sign of a missing index. It is often the correct plan, and it is the only plan that can run when no usable index exists.
Index scan
An Index Scan walks the B-tree to find matching entries. For each entry it follows the stored row pointer (a page number and an offset, called a TID) to the heap and fetches the row. It does this one row at a time, in index order.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE id = 500000;Index Scan using orders_pkey on orders
Index Cond: (id = 500000)
Buffers: shared hit=4A primary key lookup returns at most one row, so the cost is a few index pages plus one heap page. This is the case index scans are built for.
An Index Scan has two properties to remember:
- It returns rows in index order. A query with
ORDER BY id LIMIT 10can read ten entries and stop, with no sort. - Each row costs a heap visit, and those visits follow the index order, not the physical order. If the matching rows are spread over many pages, the same heap page can be read repeatedly.
Bitmap scan
A bitmap scan exists for the middle ground: too many rows for one-at-a-time random access, too few for a full table read. It runs in two steps, and the plan shows two nodes.
- A Bitmap Index Scan reads the index and builds an in-memory bitmap of the heap pages (and rows within them) that contain matches.
- A Bitmap Heap Scan reads those pages in physical order, once each, and rechecks rows as needed.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;Bitmap Heap Scan on orders
Recheck Cond: (customer_id = 42)
Heap Blocks: exact=98
-> Bitmap Index Scan on orders_customer_idx
Index Cond: (customer_id = 42)Each customer has about 100 rows, and because the data was inserted in random order, those rows sit on about 100 different pages. The bitmap lets PostgreSQL visit each of those pages once, in disk order, instead of bouncing through the heap in index order.
Exact and lossy bitmaps
The bitmap must fit in work_mem. When it does, it tracks individual rows, and the heap node reports Heap Blocks: exact=N. When it does not fit, PostgreSQL degrades the bitmap to track whole pages. The node then reports lossy=N, and every row on those pages must be rechecked against the condition. This is what the Recheck Cond line is for. A plan with many lossy blocks suggests that raising work_mem could help.
Combining indexes
Bitmaps from several indexes can be combined with BitmapAnd and BitmapOr nodes before the heap is read. This lets two single-column indexes serve a query with conditions on both columns. The cost is that a bitmap scan returns rows in physical order, so it cannot provide sorted output.
Choosing between them
The diagram is a simplification. The real decision compares estimated costs for every candidate and also considers sort order, LIMIT, parallelism and how well the physical row order matches the index order.
| Scan | Reads index | Reads heap | Output order | Best when |
|---|---|---|---|---|
| Seq Scan | No | All pages, in order | Physical | Many rows match, or no index applies |
| Index Scan | Yes | One row at a time | Index order | Few rows match, or sorted output with `LIMIT` helps |
| Bitmap Heap Scan | Yes | Matching pages, in order | Physical | A moderate number of scattered rows match |
The role of correlation
ANALYZE records, for each column, how closely the column's order matches the physical row order. You can see it in pg_stats:
SELECT attname, n_distinct, correlation
FROM pg_stats
WHERE tablename = 'orders'
AND attname IN ('id', 'customer_id', 'created_at');id is filled in increasing order, so its correlation is near 1. customer_id is random, so its correlation is near 0. High correlation makes an Index Scan cheaper, because consecutive index entries land on the same or neighboring pages. Low correlation pushes the planner toward bitmap scans.
Experiment safely
You can force the planner's hand to compare plans. The enable_* settings do not forbid a method. They add a very large cost penalty to it. Scope the change to one transaction so it cannot leak into other work.
BEGIN;
SET LOCAL enable_bitmapscan = off;
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;
ROLLBACK;With bitmap scans disabled, the planner usually picks a plain Index Scan for this query. Compare the Buffers lines. The Index Scan typically reports more buffer accesses than the Bitmap Heap Scan, because it revisits heap pages.
Why this matters for covering indexes
Both Index Scan and Bitmap Heap Scan share one cost: each match leads to a heap page. In the customer_id = 42 query above, almost all of the work is those roughly 100 heap page visits. The query needs only customer_id and total, yet the index holds no total, so the heap must supply it.
An Index Only Scan is a fourth method that can skip the heap when the index holds every column the query needs. The following chapters explain when it can do so and how to design indexes for it.
Common mistakes
- Treating every Seq Scan as a problem. For a query that returns a large share of the table, it is the cheapest plan.
- Reading
rows=in a plan without comparing estimated and actual values. A large gap points to stale statistics, and stale statistics cause wrong scan choices. - Judging a plan from a single cold run. The first run reads from disk. Run the query twice and look at
Buffers: shared hitagainstread. - Expecting sorted output from a Bitmap Heap Scan. If the query has
ORDER BY, the plan adds a Sort node or picks a different scan.
Exercise
The query SELECT * FROM orders WHERE customer_id BETWEEN 1 AND 3000 matches about 30% of the table. Which scan do you expect, and why would an Index Scan or Bitmap Heap Scan be a poor choice?
Show answer
A Seq Scan (likely parallel). With 30% of rows matching and no correlation between customer_id and physical order, the matching rows are spread over nearly every heap page. An Index Scan would revisit pages repeatedly in random order. A bitmap scan would end up reading almost all pages anyway, plus the cost of building the bitmap. Reading the heap once, in order, is cheaper.
Exercise
A Bitmap Heap Scan node reports Heap Blocks: exact=40 lossy=900. What does this mean, and what setting would you try changing first?
Show answer
The bitmap did not fit in workmem, so PostgreSQL stored 900 pages as whole-page entries instead of individual rows. Every row on those pages must be rechecked against the condition, which costs extra CPU. Raising workmem (for the session or query) lets the bitmap stay exact.