Highlights

Contents

Part V
05

Storage and indexes

Finding a seat requires navigating physical storage. Pages and indexes organize that work. Explain slots, tree intervals, and access patterns before comparing space or lookup counts.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Database model2Keys and ER3Algebra and SQL4Dependencies5Storage and indexes6Query execution7Transactions8Concurrency control9Recovery and engines10Distributed databases11Application design12The complete query

#Section 23The storage engine and locality

Returning one seat state can require index navigation, a heap page, and a visibility check. Logical values are smaller than the storage units that serve them.

A storage engine organizes records, access paths and persistence beneath query execution. A record is the stored representation of a logical row. A page, also called a block in many contexts, is a fixed-size unit the engine reads, caches or writes. Large values can span pages or live outside an ordinary row; one tuple does not necessarily equal one page-local record.

THE EXECUTOR REQUESTS PAGES THROUGH THE BUFFER MANAGERTHE EXECUTOR REQUESTS PAGES THROUGH THE BUFFER MANAGERSELECT ...WHERE seat = A7planner + executorbuffer pool in RAMP0P1P2persistent page filemiss / flusha buffered page is a working copy of persistent storage
Figure 1.26The layers turn a logical query into storage requests. A RAM-resident page can satisfy a request without a device read.

RAM allows direct access to resident bytes. Persistent devices retain data after power loss, but have their own latency, transfer granularity and durability semantics. Sequential I/O visits nearby locations in order; random I/O jumps between locations. SSDs remove mechanical seeks but do not make every pattern identical in cost. Reusing nearby rows and pages gives locality, which helps both caches and device access.

A heap file stores table records without maintaining the table in a particular key order. The engine tracks free space to choose pages for inserts. Indexes point into that heap or into another primary organization. An operating system page cache and a database buffer pool can both cache data depending on the I/O strategy; their names do not imply they are the same cache.

One tuple request can cause several distinct accesses

An index entry might identify a heap page and a slot. The executor asks the buffer manager for that page. If it is already resident, no device read is needed; otherwise the manager chooses a frame, obtains the page from backing storage and makes it available. The storage code then follows the slot to the record and the visibility code decides whether that record belongs to the query’s snapshot.

These are different costs. An index navigation count measures logical page accesses. A cache miss count measures requests that need a lower-layer fetch. A device read count depends further on the operating system’s cache and I/O mode. “The query accessed a page” does not prove it performed a physical SSD read.

Sequential access tends to reuse nearby pages and can allow prefetching. A secondary lookup can jump between heap pages even when its own index entries are adjacent. Two queries returning the same number of tuples can therefore move different numbers of pages through the caches. This is why query plans need page and locality evidence as well as row counts.

#Section 24Slotted pages and usable space

A slotted page keeps a stable slot identifier while record bytes move. Index references need not track every variable-length update’s new byte offset.

The header holds page metadata and space boundaries. A slot directory grows from one side and records grow from the other. A slot records the location and size of its item. Compaction can move record bytes while updating the slot entry. Row locators can use a page identifier and slot identifier, although update semantics and locator stability differ by engine.

ILLUSTRATIVE SLOTTED PAGE: 4,096 BYTESheader: 64 bytes31 slots × 4 bytesfree: 64 bytes31 records × 124 bytesslots growrecords growschematic heights; byte sizes are exact
Figure 1.27Illustrative Heron page. Band heights are schematic, not proportional; all labelled byte counts are computed from the declared toy layout.

For fixed-size Heron records, page capacity is

Page capacity counts whole records after header and slot overhead. Free space is part of the page, not an additional record.

Real occupancy also depends on alignment, variable values, versions, and reserved growth space. The drawing’s packed layout is illustrative.

Free-space tracking locates insertion room without scanning every page. Deleting a record need not return its page to the filesystem. PostgreSQL page layout.

Insert, move and delete inside a page

For an insertion, the engine first checks that the page has enough room for both the record and its slot entry. It allocates a slot, places the record in free space and makes the slot point at that location. The page’s free-space boundaries change. A free-space directory can then advertise the remaining room to later insertions.

If record bytes move during compaction, the slot keeps its identity while its location field changes. A reference through that slot still finds the item under the engine’s locator rules. If the record is deleted, the engine may first mark a logical deletion because snapshots or recovery can still need it. Reclamation happens only when those obligations allow it. A hole inside a page is not automatically a free filesystem block.

Reserving room for later growth uses more space but can reduce movement or splits. Maximum packing is not always the best write policy.

#Section 25Why B+ trees have high fanout

Database trees put many entries on each page, letting one fetched node narrow the search substantially. A separately stored binary node would waste that transfer.

A B-tree is a balanced multiway search tree. A B+ tree keeps record references or data at its leaves, with separator keys in internal nodes and leaf links for ordered traversal. The fanout is the number of child branches an internal node can select. All leaves have the same depth, so the tree’s height bounds the navigation path.

ILLUSTRATIVE PACKED INDEX: ROOT AND FOUR LEAVESroot: separators252 entries252 entries252 entries44 entriesmatching heap pagelinked leavesserve ranges
Figure 1.28Illustrative packed Heron index: 800 entries occupy leaves of 252, 252, 252 and 44 entries. One root selects a leaf, whose matching entry locates a heap row.

A high-fanout tree places many entries per leaf. A point lookup traverses its routing pages, then the row’s storage where needed. Cached page visits are not mandatory device reads.

Navigate child intervals to a matching leaf. For a range, continue through adjacent leaves rather than returning to the root for every key. High fanout reduces page navigation, while the actual height depends on occupancy.

High fanout comes from compact separators and page-sized nodes. Wider keys lower capacity. Partly filled nodes, duplicate handling and internal-node layouts also affect height. The algorithmic reason for B+ trees survives these details: spend a page read to examine many possible branches and keep range data in leaf order.

Follow an equality lookup and then a range

For a point lookup, the root separators identify which leaf’s key interval can contain the requested show-seat pair. The engine searches that leaf’s sorted entries and follows a matching locator to a heap page. It verifies that the row matches the query and its visibility rules before returning state. If the root and leaf are cached, their logical accesses need not become device reads.

For a range, locate the first qualifying key in the same way. Consume the remaining qualifying entries in that leaf, then follow the next-leaf link while the upper boundary still permits matches. The links avoid a fresh root traversal for every consecutive key. They do not eliminate heap access when the requested data or visibility information is absent from the index.

The example’s leaf count assumes fixed overhead and dense occupancy. Separator encoding, duplicates, and later growth change a live tree’s storage.

#Section 26Inserts, splits, deletes and merges

A full leaf cannot gain space by shifting entries. Splitting must preserve ordered search intervals and propagate structural changes correctly.

An insert searches to the target leaf, inserts in key order, and checks capacity. If the leaf overflows, a split distributes its entries between two leaves and installs a separator in the parent. If that parent overflows, splitting propagates upward. Splitting the root creates a new root and increases the height; all leaves still remain at the same depth.

ILLUSTRATIVE LEAF CAPACITY: FOUR KEYS10203040insert 25; the leaf overflows1020253040leaf linkleft leafright leaf; parent gains separator 25
Figure 1.29Illustrative capacity-four leaf. Inserting 25 into 10, 20, 30, 40 creates five entries, split here into two and three; separator 25 guides the right branch.

A delete removes an entry under the engine’s visibility and reclamation rules. A textbook underfull node can borrow entries from a sibling or merge with it, followed by parent-separator repair. Removing the last useful root level can reduce the height. Production engines may defer physical removal, use different occupancy policies or avoid eager merges; describe the invariant rather than assuming the textbook timing is universal.

Structural modifications must be safe while other workers search or update the same tree. A short physical latch protects an in-memory data structure while it changes. A transaction lock protects a logical concurrency rule for a longer lifetime. Mixing the two concepts leads to explanations in which every tree traversal would block unrelated transactions until commit.

Splits add write work and can reduce page density. Insert order, reserved free space and key width affect their frequency. A unique index must coordinate concurrent equal-key inserts so both cannot pass a stale independent check. “First SELECT, then INSERT” in application code does not recreate that engine guarantee.

Repair the parent as well as the leaf

Insert into a full leaf by splitting its ordered entries and adding the new boundary to the parent. Update leaf links so later range scans include the new neighbor.

If the parent did not change, a correct new leaf could remain unreachable through the old navigation tree. If the sibling links did not change, a range scan could skip the new keys. A split is therefore a coordinated change to search navigation and ordered traversal. The engine’s concurrency algorithm must keep searches correct while that change occurs.

Deletion may require borrowing or merging and updating parent separators. Moving a key across leaf boundaries changes the routing interval too; the figure shows how the parent must follow that change.

If neither neighboring leaf can donate while preserving minimum occupancy, merge them and remove the obsolete parent pointer. A root with only one surviving child may shrink.

B+ TREE DELETE: AN UNDERFULL LEAF BORROWS FROM ITS SIBLING, OR THE TWO MERGEB+ TREE DELETE: AN UNDERFULL LEAF BORROWS FROM ITS SIBLING, OR THE TWO MERGEunderfull: left has 1 key2510253040borrow 25, separator → 30301025304025later delete 25 and 4010301030merge: parent loses one child pointermin 2, max 4 keys per leaf (illustrative)
Figure 1.30Illustrative minimum-two, maximum-four leaf occupancy. Borrowing changes a separator; merging removes a child pointer.

These repairs explain why an index insert or delete costs more than writing one isolated entry.

#Section 27Hash, clustered and secondary indexes

Hashing groups equal keys; it does not preserve the ordering needed for a ticket-price range scan.

A hash index maps keys to buckets, then checks actual key equality inside a bucket because collisions exist. Equality lookup can be efficient, but a range generally needs another access path. Hash growth may require bucket splits or a directory. Do not promise constant worst-case time or confuse a hash join’s temporary table with a persistent hash index.

A clustered organization arranges the table’s data through the primary ordered structure, or in terminology specific to an engine, maintains rows near that key order. A secondary index, often called non-clustered, stores an alternative key order and a locator for rows kept elsewhere. The exact locator may be a physical row reference or a primary key, affecting entry size and the work of another lookup.

AN INDEX ENTRY CAN POINT TO A ROW ON A DIFFERENT HEAP PAGEAN INDEX ENTRY CAN POINT TO A ROW ON A DIFFERENT HEAP PAGEindex leaf, sorted by keyA7locatorA8locatorA9locatorB1locatorheap pages, physical orderB1A9A7C4A8B6key order and row placement are separate choices
Figure 1.31Index structure and table organization are separate choices. “Clustered” needs an engine-specific definition.

Several secondary indexes can coexist, but one heap cannot maintain several physical orders without copies. PostgreSQL CLUSTER reorders a table once; later writes do not automatically retain that order. CLUSTER reference.

Choose by workload. Equality-only access can suit hashing; equality plus ranges often suits a B+ tree. Secondary indexes provide several access patterns at the cost of more stored structures and write maintenance. None removes the need to inspect selectivity and query plans.

Compare the physical routes for one result

With a secondary email index, a lookup finds an email entry and then follows its row locator into the user’s primary storage. If the locator is a physical heap reference, it leads toward a page and slot. If the engine stores a clustered primary key as the locator, it may require another tree lookup. The same SQL query can therefore have a different physical route in two engines.

A hash bucket gives another route. Hash the requested id, visit its bucket and check actual keys within it. Two different keys can share a bucket, so the equality check is still necessary. A request for ids between two bounds cannot derive a useful adjacent-bucket walk merely from numeric order; the hash function intentionally destroys that ordering.

For a clustered range, row bodies corresponding to adjacent index keys tend to be in the primary ordered organization. That can reduce scattered row retrieval, but maintaining several different physical row orders would require several copies. Secondary indexes preserve alternative key orders cheaply in terms of row duplication, while still paying for locators, payloads and write maintenance.

#Section 28Composite indexes and leftmost prefixes

An index on (show_id, state, seat_id) groups by show first. Without a show predicate, free seats can be scattered across many groups.

A composite index orders by several key attributes, usually lexicographically for a B-tree. The leftmost-prefix rule is a useful access-path principle: equalities on leading attributes select a contiguous region, and a condition on the next attribute can bound that region. Conditions after an unconstrained or ranged attribute may still filter entries without narrowing the same single interval.

AN INDEX ON (a, b, c) IS SORTED LIKE A PHONE BOOK: FIX a, THEN b NARROWS INSIDE ITAN INDEX ON (a, b, c) IS SORTED LIKE A PHONE BOOK: FIX a, THEN b NARROWS INSIDE ITabceast1A7east1A8east2A7west1A7west2A7a = east: one rangea = east AND b = 1: smaller rangeb = 1 alone: rows 1, 2 and 4, scatteredacross every a group; the order does not help
Figure 1.32Illustrative order. Fixing a selects a region, and fixing a and b selects a smaller region. A b-only predicate is distributed across different a groups.
Predicate on index (a,b,c) Usual navigation consequence
a = ? Bound the a group
a = ? AND b = ? Bound the a,b group
b = ? No single ordinary leading-key interval
a = ? AND c = ? Bound a; use c inside that region
a = ? AND b > ? AND c = ? Bound a and a range of b; c may filter

Missing a leading predicate does not forbid every index use. Full scans, index combinations, and supported skip scans can still help; the limitation concerns an ordinary narrow leading-key interval. Multicolumn indexes.

Column order also affects sorting. An index can provide an ORDER BY compatible with its key ordering after fixed leading keys. Collations, NULL ordering and direction matter. Design a composite index for a concrete filter-and-order pattern, and verify whether it reduces scanned entries rather than merely appearing in the plan.

Think in contiguous intervals

Fixing the leading attributes selects contiguous nested groups. A predicate on only a later attribute can scatter matches across those groups, as the figure shows.

A predicate on a and c still benefits from the bounded a region. The c test can discard entries inside it, even though the intervening b attribute remains unconstrained. That explains why “the index is useless” is also too strong. The question is how much of the index must be traversed before the engine knows all matches have been found.

A range on b can leave several b groups to scan. Filtering c within them does not necessarily shrink the outer endpoints of that range. Some engines can perform several distinct probes or choose skip-scan strategies under suitable distributions. A query plan will tell you whether it navigated a narrow interval, repeatedly probed groups or scanned a broad region.

#Section 29Covering, partial, expression and unique indexes

Including requested values can avoid a heap fetch, subject to visibility rules. It also enlarges the index and its maintenance work.

A covering index contains the requested values. An index-only scan also needs visibility evidence; PostgreSQL can use its visibility map, but recent updates can still require heap checks. Reference.

COVERAGE SUPPLIES DATA; VISIBILITY CHOOSES THE ROUTEindex entry + payloadpage all-visible?return from indexyesfetch heap versionnocheck visibilityreturn or discard
Figure 1.33PostgreSQL’s conceptual covering path. A covering definition enables index-only data retrieval but does not promise zero heap fetches.
sql
CREATE INDEX show_seat_state
ON show_seats(show_id, seat_id) INCLUDE (state);

The included state is payload rather than another navigation key. A unique index enforces uniqueness under its declared semantics. A partial index stores only rows meeting a predicate, such as active reservations. The query must imply that predicate for the planner to rely on its coverage. An expression index stores the result of an expression, such as lower(email), so a matching search avoids calculating it over every table row.

Why not index every column? Inserts and deletes maintain every relevant structure; updates maintain indexes whose keys or payload change. Indexes occupy storage and cache space, generate logged work and can split pages. Included wide values make leaf entries larger. Expression and partial definitions also encode semantics: case-folded uniqueness and “active” membership must be the intended business rules.

A partial unique index can express a real lifecycle rule

Suppose historical booking items may retain cancelled purchases, but only held or sold claims should block the same show seat. A partial unique index on (show_id, seat_id) restricted to active status can enforce one active claim while allowing cancelled history. The predicate must represent the actual lifecycle, and every status transition into the indexed set must pass the uniqueness check.

An expression index on lower(email) expresses a different decision: searches or uniqueness operate on the normalized expression, not the original spelling. The application must use compatible case and collation semantics. Such an index does not mean every unrelated expression on email can use the same stored value.

For a covering seat-state query, state as included payload can avoid a heap data lookup, but it also changes the entry whenever state changes. Heron’s hot inventory is updated often, so visibility and write-maintenance costs matter. Include values because a measured access pattern benefits, not because larger indexes sound more complete.