Heap and Index: Two Separate Structures

Two structures, usually two files

1. Indexes (B-trees)

Store index tuples: key → row pointer. Small, sorted, many-per-table. Purpose: fast lookup.
e.g. email="john@ex.com" → record #1

2. Heap (table pages)

Store full rows — all columns — plus per-row metadata such as MVCC stamps. Large, unordered, one per table. Purpose: hold the complete records.
e.g. #1 = {user_id:1, email:john@ex.com, age:25}

Disk layout, and what a pointer actually is

Take a three-row users table (user_id, email, age). The database file is a flat sequence of fixed-size pages — 8 KB in Postgres, 16 KB in InnoDB. Each page has a header identifying its type: heap row page, B-tree node, free-space map, and so on.

One file on disk as five fixed-size pages. Pages 0 and 1 are heap pages holding rows; page 2 is a B-tree leaf of the email index; page 3 is free; page 4 is a B-tree leaf of the user_id index. Each page header carries a type field that tells the database how to interpret the block.
One flat file, pages of different types — the header says which
The email index leaf page holds three entries in key order: bob points to TID page 1 slot 2, jane to page 1 slot 1, john to page 0 slot 0. Each TID leads to an exact slot in a heap page: heap page 0 slot 0 holds user 1, john, age 25; heap page 1 slot 1 holds user 2, jane; slot 2 holds user 3, bob.
The index stores key → TID; the TID names one slot on one heap page

The pointer stored in an index leaf is a TID (Tuple ID) — (page_number, slot_number). An exact physical location, not a vague range.

How the index changes size

  • Growth: when an index page fills, the B-tree splits it — a new page is allocated from the Free Space Map, and the parent gains a pointer. The index expands one page at a time, wherever free pages exist.
  • DROP INDEX: pages are marked free in the FSM and reused by future inserts or other indexes. They are not returned to the OS immediately; VACUUM can truncate trailing empty pages to shrink the file.
  • CREATE INDEX: scan the heap, sort the entries, write out fresh B-tree pages.
  • Fragmentation: splits and deletes leave gaps over time. REINDEX rebuilds cleanly from scratch; VACUUM reclaims dead heap rows.

How CREATE INDEX CONCURRENTLY guarantees nothing is missed

It runs in phases, tiling two time windows together using PostgreSQL's own snapshot/visibility machinery:

  1. Register, invisible. The index enters the catalog with indisready = false, indisvalid = false. Nothing uses it or maintains it yet. Wait for every transaction that might not see the new catalog row.
  2. First heap scan. Take a snapshot, scan the whole heap, build entries for every row visible at that snapshot. No table lock held.
  3. Mark write-ready.indisready = true. Queries still ignore it, but every INSERT/UPDATE/DELETE from this point maintains index entries. Wait for transactions that started before the flag flipped, so nobody is still writing without maintaining it.
  4. Second heap scan. Take a newer snapshot and re-scan for rows the index is missing — anything inserted between snapshot 1 and the write-ready flag, the gap where writes were happening but nobody was maintaining the index.
  5. Wait, then mark valid. Wait until every transaction that started before the second scan has finished, so no query is running against a view of the table predating the index. Then indisvalid = true. The index is live.

Nothing is missed because the first scan covers everything before the build started, the write-ready flag captures every write after it, and the second scan plugs the gap between those two moments.

How the sort avoids overwhelming RAM — external merge sort

PostgreSQL never tries to sort the whole table in memory.

Step 1. Build sorted runs. Read the heap in chunks that fit in maintenance_work_mem (default 64 MB for index builds), sort each chunk in memory, spill it to a temp file as a sorted run. Repeat until the heap is consumed.

Step 2. k-way merge. Open all run files at once. Keep a min-heap in memory with one slot per run; pull the smallest key across all runs, write it to output, advance that run's pointer.

Three sorted runs on disk: run 1 starts 20, 25, 31; run 2 starts 18, 22, 40; run 3 starts 19, 28, 35. A min-heap in memory holds one slot per run, the current head of each: 20, 18 and 19. It pops the smallest, 18, writes it to the output and advances run 2. The output stream reads 18, 19, 20, 22 and so on.
The k-way merge holds one head per run, never the table

RAM during the merge is one page per run file — tiny regardless of table size.

Step 3. Write B-tree pages. The sorted stream of (key, TID) pairs is written directly as leaf pages; internal nodes are then built bottom-up from the leaf level.

A 500 GB table with 64 MB of maintenance_work_mem produces ~8,000 sorted runs; the merge phase still needs only ~8,000 read-buffer slots — a few hundred MB, not 500 GB. Raising maintenance_work_mem means fewer, larger runs and fewer merge passes.

A query, end to end

SELECT age FROM users WHERE email = 'john@example.com'

Step 1 — navigate the email index
  B-tree leaf: 'john@example.com'  →  TID = (page=23, slot=5)

Step 2 — jump to the exact page and slot
  load heap page 23 into the buffer pool          (1 disk read)
  slot 5 → byte offset 1,240 within that page
  read row: {user_id:1, email:john@example.com, age:25}
  extract age = 25

Total: ~4 page reads (3 for the B-tree descent + 1 heap page)

How a page number becomes a byte on disk

byte_offset = page_number × 8192 → pread(fd, buffer, 8192, byte_offset)

one arithmetic operation, one syscall, O(1). The OS seeks to that offset and reads exactly 8 KB.

Inside a single page

One 8 KB slotted page laid out from byte 0 to byte 8192, not to scale. A 24-byte page header, then the slot array, which grows forward: slot 1 holds offset 8112, length 80; slot 2 holds offset 8052, length 60. Free space sits in the middle. Tuples are written from the end of the page backward: tuple 1 occupies bytes 8112 to 8192, tuple 2 bytes 8052 to 8112. A TID slot number indexes the slot array, and the slot offset locates the tuple bytes — two pointer chases, both in RAM.
Inside one page: slots grow from the front, tuples from the back Not to scale — the header and slot entries are a few bytes each (a PostgreSQL line pointer is 4 bytes); the free space between the two growing regions is what an insert consumes.
  • slot_number indexes into the slot array — each entry fixed-size (offset + length).
  • slot[n].offset is the byte offset within this page where the tuple starts.
  • Total: two pointer chases from TID → tuple bytes, both in RAM.

File segmentation: which file holds page N?

A table's pages form one continuous logical address space, but PostgreSQL never lets a single OS file exceed 1 GB. Each segment holds exactly 1 GB ÷ 8 KB = 131,072 pages.

Why 1 GB, and why split at all:

  • Portability across file-size limits. Some filesystems and platforms Postgres historically supported capped a single file at 2–4 GB (32-bit off_t, old FAT variants). Capping at 1 GB — well under any known limit — sidesteps this everywhere without per-OS special-casing.
  • Tooling friendliness. cp, tar, rsync and backup scripts behave better on bounded-size files than on one multi-hundred-GB monolith.
base/<db_oid>/<relfilenode>      ← pages 0 – 131,071
base/<db_oid>/<relfilenode>.1    ← pages 131,072 – 262,143
base/<db_oid>/<relfilenode>.2    ← pages 262,144 – 393,215

segment_number        = page_number / 131072
offset_within_segment = (page_number % 131072) × 8192

This is still pure arithmetic — no lookup table. And it is not a claim about physical disk layout: it's a logical split of one relation's byte-address space into bounded OS files, orthogonal to the extent-map question from the SSTables and sparse indexes part. Whether the bytes inside one segment are physically contiguous is the filesystem's business, same as any other file.

Where the relfilenode lives: the table-name → physical-file mapping is in the system catalog pg_class (SELECT relname, relfilenode, reltablespace FROM pg_class WHERE relname='users'). That catalog row is itself in a system heap file and is cached in shared memory after the first lookup, so normal queries never re-read it from disk.

full path from TID to bytes

TID = (page=170000, slot=5)
  │
  ├─ segment = 170000 / 131072 = 1        → open file "<relfilenode>.1"
  ├─ offset  = (170000 % 131072) × 8192
  │           = 38928 × 8192 = 318,898,176 bytes into that file
  │
  pread(fd, buf, 8192, 318898176)         → 1 disk read, 8 KB page in RAM
  │
  └─ slot[5].offset = 1240                → tuple starts at byte 1240 in the page

One page, many records — why slots exist

A typical 8 KB heap page holds 50–200 rows. Records are variable-size, so without a slot array you would have to scan record 1 → 2 → 3 to find where record 3 starts. The slot array sits at a known position (top of page) with fixed-size entries, so:

slot_array_start + (3 × slot_size) → read offset value (490) → jump to byte 490

two arithmetic operations. Constant time regardless of how many records are on the page.

This is also why external indexes store (page, slot) rather than a raw byte offset: if a record moves within its page during compaction, only the slot's offset value changes — every index pointing at it stays valid.

Why this design

BenefitBecause
Fast lookupIndexes are small sorted B-trees — navigate to the record ID, then jump straight to it.
Multiple indexesEmail, user_id and age indexes live independently without duplicating the data.
Efficient storageData is stored once, in the heap. Indexes only point at it.
Each optimized for its jobHeap pages hold whole rows plus MVCC metadata; B-tree pages hold many small sorted tuples. Heap stays good for writes (write the full row once); index stays small (key + pointer only); range queries work because index keys are sorted.

✓ The cost you pay

With index:
  read index pages → find record ID
  read data page   → get the actual row
  Total: 2 disk accesses (min)

✗ The alternative, and why it's worse

Store key + entire row inside the index:
  read 1 index page → get everything
  ...but now every index duplicates
  every column of every row.

Three ways to lay out the data itself

MethodLayoutAdvantageDisadvantage
Heap storage (most common — PostgreSQL)Records in arbitrary order; indexes point inFast inserts — just find room and appendEvery lookup needs an index
Clustered index (SQL Server, MySQL InnoDB)Records stored sorted by primary keyPK lookups are one step — no second jump to a heapInserts are slower; order must be maintained
Column store (analytics — see Analytics and table formats)All values of one column stored togetherFast analytical scans over a few columnsSlow full-row lookups

What if one column value is bigger than a page?

PostgreSQL pages are 8 KB, and a single column value can be far larger. It is not stored inline. PostgreSQL uses TOAST (The Oversized-Attribute Storage Technique):

  1. The heap row keeps a normal tuple header plus its small inline fields.
  2. If a field is too large, PostgreSQL first tries to compress it.
  3. If it's still too large, the value is stored out of line — broken into chunks in a separate per-table TOAST table — and the heap row keeps only a small TOAST pointer.
Heap row on page 891:
  id    = 123
  title = "big document"
  body  = TOAST_POINTER( toast_table_oid, chunk_ids... )

TOAST table:
  chunk 0 -> first piece of body
  chunk 1 -> next piece
  ...

The practical rule: rows never span heap pages; large column values move out of line; the base row stays small enough to fit a normal page.

The Invariants

  • Guarantees: A TID resolves to exact bytes in O(1) arithmetic plus two in-RAM pointer chases, and stays valid while the row moves within its page.
  • Does not guarantee: That a TID still points at the row you meant — a row that moves to a different page gets a new TID, and the old index entry lingers until VACUUM (see VACUUM and free space). Nor does the index know anything about visibility; that is resolved entirely at the heap (see MVCC and visibility).