Sub topic 1
Where the data lives: heap tuples and B-tree entries
Prerequisites
This chapter assumes you can write SELECT, WHERE and CREATE INDEX, that you know at a high level what a B-tree index is, and that you can run EXPLAIN and read a simple plan.
Heap tuples and index entries
PostgreSQL stores table rows in a structure called the heap. A heap tuple is one stored version of a row. A B-tree index is a separate structure. Each index entry holds a key value and a pointer to a heap tuple. A lookup through an index therefore has two steps: search the B-tree, then fetch the heap tuple.
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id integer NOT NULL,
total numeric(10,2) NOT NULL
);
CREATE INDEX orders_customer_idx ON orders (customer_id);How PostgreSQL scans
- Sequential scan: reads every heap page. The planner picks it when a query touches much of the table.
- Index Scan: walks the B-tree, then fetches each matching heap tuple.
- Bitmap Heap Scan: collects matching pointers into a bitmap, orders them by heap page, and reads each page once.
What an index-only scan is and what it needs
An index-only scan answers a query from the index and skips the heap. Every column the query returns must be in the index. In the table above, total is not in orders_customer_idx, so a query that selects total still reads the heap.
The visibility map: why the index alone is not enough
Index entries do not record which transactions can see a row. That information lives in the heap. The visibility map is a per-table file with bits for each heap page. The all-visible bit means every tuple on that page is visible to all transactions. Only then can PostgreSQL skip the heap for that page.
VACUUM and the all-visible bit
VACUUM removes dead tuples and sets the all-visible bit on pages where every tuple is visible to all. Updates and deletes clear that bit on the pages they change. Until the next VACUUM, index-only scans must check the heap for those pages.
VACUUM (ANALYZE) orders;Exercise
After a large UPDATE on orders, why might an index-only scan still read the heap?
Show answer
The UPDATE cleared the all-visible bit on the pages it changed. The planner must check the heap for those pages until VACUUM sets the bit again.