Sub topic 1
Where the data lives: heap tuples and B-tree entries
This chapter describes the two physical structures behind almost every PostgreSQL query: the table heap and the B-tree index. Later chapters on index-only scans and covering indexes depend on one fact from here. An index entry and a table row are stored in different places, and PostgreSQL has to link them.
Prerequisites
This chapter assumes you can do the following:
- Write basic SQL:
SELECT,WHERE,CREATE TABLEandCREATE INDEX. - Describe a B-tree index at a high level, as a sorted structure that finds values quickly.
- Run
EXPLAINand read a simple query plan.
You also need a PostgreSQL server (version 11 or later, because later chapters use INCLUDE) and a database where you can create tables. The examples use the orders table from the Topic Spine, which has one million rows.
The table heap
PostgreSQL stores each table as a heap. A heap is a file of fixed-size pages, with no ordering by any column. Each page is 8 kB by default. Rows go wherever there is free space.
Each row version stored in a page is called a heap tuple. A tuple holds:
- A small header with bookkeeping fields. Among them are the IDs of the transactions that created and deleted the tuple, which are used for visibility checks.
- The column values, in table order.
A page also has an array of line pointers near its start. Each pointer says where one tuple lies inside the page. Other parts of the system refer to a tuple by its page number and its line pointer number, not by its byte offset. That lets PostgreSQL move a tuple within a page without breaking references to it.
The tuple identifier (TID)
The address of a tuple is its TID (tuple identifier). It is a pair: (page number, line pointer number). You can see it through the hidden ctid column:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id integer NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
note text
);
INSERT INTO orders (customer_id, status, total, created_at)
SELECT (random() * 10000)::int,
(ARRAY['new','paid','shipped','cancelled'])[1 + (random() * 3)::int],
(random() * 500)::numeric(10,2),
now() - random() * interval '365 days'
FROM generate_series(1, 1000000);
SELECT ctid, id, customer_id, total
FROM orders
ORDER BY id
LIMIT 5;The first few rows show ctid values such as (0,1), (0,2) and (0,3). These mean page 0, line pointers 1, 2 and 3. The exact values on your server depend on row width, but the pattern is the same.
Row versions and MVCC
PostgreSQL uses MVCC (multiversion concurrency control). An UPDATE does not overwrite a row. It writes a new tuple and marks the old one as ended by the updating transaction. A DELETE only marks the tuple as ended. Readers with older snapshots can still see the old version.
This has a consequence that matters for this tutorial. Whether a tuple is visible to your query depends on transaction information stored in the tuple header. As the next section shows, B-tree entries do not carry that information.
The B-tree index
A B-tree index is a separate on-disk structure, also made of 8 kB pages. It keeps entries sorted by the indexed columns, so PostgreSQL can find a value by walking down from a root page, through internal pages, to a leaf page.
The pages come in three kinds:
- The root page is the entry point. In a small index, it can also be the only leaf.
- Internal pages hold separator keys and downlinks that direct the search.
- Leaf pages hold the actual index entries, in sorted order. Leaf pages are linked to their neighbors, so a range scan can move sideways without returning to the root.
What a leaf entry contains
Each leaf entry holds two things:
- The indexed column values, called the key.
- The TID of a heap tuple that has those values.
The entry does not hold the other columns of the row, and it does not hold the transaction visibility information. For an index on orders (customer_id), an entry is roughly (customer_id = 42, TID = (7,3)).
This design explains two behaviors:
- If a query asks for a column that is not in the index, such as
total, PostgreSQL must follow the TID to the heap to read it. - Even if a query asks only for indexed columns, PostgreSQL still has to check whether the tuple is visible to the current snapshot. The index entry cannot answer that, so the default is to visit the heap.
The second point is the reason the visibility map exists. Later chapters cover it. For now, remember that a plain index entry tells you where a row is. It does not tell you whether you may see it.
Multiple entries for one row
An index contains one entry for each tuple version, not one for each logical row. When an UPDATE changes a row, PostgreSQL normally has to add a new entry to every index on the table, because the new tuple has a new TID. There is an optimization called a HOT update (heap-only tuple), which skips the index insert when no indexed column changes and the new tuple fits on the same page. The chapter on write costs returns to this. Note now that adding more columns to an index makes HOT updates less likely, because more columns can change.
Seeing both structures at work
Create an index and refresh the planner statistics, then look at the sizes of the heap and the index:
CREATE INDEX orders_customer_idx ON orders (customer_id);
VACUUM (ANALYZE) orders;
SELECT pg_size_pretty(pg_relation_size('orders')) AS heap_size,
pg_size_pretty(pg_relation_size('orders_customer_idx')) AS index_size;The heap is much larger than the index, since it holds every column of every row, while the index holds only customer_id and a TID per entry. On a typical installation, the heap for this table is on the order of 70 MB and the index about 20 to 30 MB. Your numbers will differ.
Now run a query and ask for buffer information:
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;The plan typically shows an Index Scan or a Bitmap Heap Scan on orders. Read the Buffers: lines. They count pages touched in the index and in the heap separately. Some pages are index pages, and some are heap pages reached through TIDs. The heap pages exist because total is not in the index.
Index entries and heap pages: a comparison
| Property | Heap tuple | B-tree leaf entry |
|---|---|---|
| Where it lives | Table file, in 8 kB pages | Index file, in 8 kB pages |
| Contents | Header plus all column values | Key column values plus a TID |
| Order | Unordered, wherever there is space | Sorted by key |
| Transaction visibility info | Yes, in the tuple header | No |
| Count after an update | New tuple, old one remains until cleanup | New entry, old one remains until cleanup |
Common mistakes
- Assuming an index holds the whole row. It holds the key columns and a TID only, unless a later chapter's
INCLUDEclause adds payload columns. - Assuming an index lookup avoids the table. A normal index scan reads the index to find TIDs and then reads the heap for each match.
- Treating
ctidas permanent. It changes when the row is updated or the table is rewritten. - Assuming the index knows which rows are visible. Visibility lives in the heap tuple header, so the index alone cannot decide it.
How this leads to index-only scans
To answer a query without touching the heap, PostgreSQL needs two things. The index must contain every column the query uses, and PostgreSQL must be able to confirm visibility without reading the tuple header. The first need leads to covering indexes. The second leads to the visibility map. The next chapters take scan types first, then these two ideas in order.
Exercise
An index on orders (customerid) has a leaf entry for customer 42 pointing to TID (7,3). A query selects customerid and total for that customer. Why can PostgreSQL not answer it from the index alone, and what are the two reasons even a query selecting only customer_id would still visit the heap in a normal index scan?
Show answer
The query needs total, which is not stored in the index entry, so PostgreSQL must follow the TID to heap page 7 and read the tuple at line pointer 3. For a query selecting only customer_id, the first reason is that the plain index scan always fetches the heap tuple. The second reason is that the transaction visibility information lives in the heap tuple header, not in the index entry, so PostgreSQL cannot tell from the index whether the row is visible to the current snapshot. Avoiding the heap visit requires a way to know visibility without the header, which is what the visibility map provides.
Exercise
Run SELECT ctid, id FROM orders WHERE id = 1; then UPDATE orders SET total = total + 1 WHERE id = 1; and run the SELECT again. What do you expect to see in ctid, and why?
Show answer
The ctid will usually change. The UPDATE writes a new tuple version rather than overwriting the old one, and the new version gets its own TID, typically on the same page with a higher line pointer number if there is free space. The old version remains until VACUUM removes it.