3.3 Insertion and Page Splits
An index must always keep its keys sorted. But is there no problem if, each time a new row is inserted, we find its sorted position and insert it in the middle? Early after a table is created, pages have plenty of free space, so there is no problem. But what if the leaf page where the new key must go is already full?
In this case the B+Tree performs a page split. It allocates a new page, moves half of the entries of the full page into it, and inserts the new key into whichever of the two pages matches its key range. Then it adds a link pointing to the new page in the parent page. If the parent page is full too, the same operation is repeated at that page. Thanks to this approach, the tree stays balanced rather than leaning to one side.
Figure 3-4. The process of a leaf page split
flowchart TB
subgraph before["before · insert key 25 into a full leaf"]
direction TB
pa["parent · [ ... | 10 -> P1 | 50 -> ... ]"] --> p1["P1 · [ 10 | 20 | 30 | 40 ] (full)"]
end
subgraph after["after"]
direction TB
pb["parent · [ ... | 10 -> P1 | 30 -> P2 | 50 -> ... ]"] --> q1["P1 · [ 10 | 20 | 25 ]"]
pb --> q2["P2 · [ 30 | 40 ]"]
q1 <--> q2
end
before ~~~ after
class pa,pb meta
class p1 warn
class q1 data
class q2 hot
The key values are examples for illustration. Before the split (before), leaf page P1 holds keys 10, 20, 30, and 40 and has no free space. The parent page has a link saying "keys 10 and above go to P1." In this state, key 25 must be inserted. In sorted order, 25 belongs between 20 and 30 in P1, but there is no room.
The after-split state is read in the following order.
- Allocate a new leaf page P2 and move the latter half of P1's entries (30, 40) to P2.
- The new key 25 is inserted into P1, which matches its key range. P1 now holds 10, 20, 25, and P2 holds 30, 40.
- Link P1 and P2 sideways to preserve the order among leaves.
- Add a link to the parent page saying "keys 30 and above go to P2." If the parent page is full too, the same split occurs in the parent page.
A split is an expensive operation. It must allocate a new page and modify multiple pages, and all those changes must be recorded in the log, which Chapter 5 covers. So how often splits occur is an important indicator of write performance.
How the key is defined plays a very important role in performance. If customer numbers increase as 1, 2, 3, ..., a new row always goes into the last leaf page. Only the last page is filled in turn, and when it is full a new page is simply appended, so splits are clean and efficient. Conversely, if the key is a randomly generated value (for example, a UUID), new rows are scattered across the index. As multiple leaf pages fill up, splits become frequent, and the buffer pool must hold leaf pages from across the whole index, which lowers cache efficiency.