Building My Own Database in C++ — Part 3: Implementing indexes
Table of Contents
Building a B+ Tree
In the previous sections, we built the storage layer of our database, including the table heap and record identifiers (RIDs). However, retrieving a record still requires scanning the table to find the corresponding key. As the number of records grows, this becomes increasingly expensive.
To improve lookup performance, we can introduce an index. In this section, we will implement an in-memory B+ tree that maps integer keys to RIDs. Instead of scanning every record, the tree directs us towards the leaf node that may contain the key we are looking for.
Our implementation supports duplicate keys: each distinct key maps to one or more RIDs. This is useful for non-unique indexes, such as an index on age where several records may have the same value. We will start with the node structure, then implement insertion and search, before handling node splits and maintaining the tree as it grows.
Understanding the structure of a B+ Tree
A B+ tree consists of two types of nodes. Internal nodes contain separator keys and child pointers, which guide the search towards the correct leaf. Leaf nodes contain the actual keys and their corresponding RIDs. In a leaf, each distinct key appears only once, but its entry can point to multiple RIDs when several records share that key.
In our implementation, each node can hold at most max_keys distinct keys before it needs to split. For simplicity, we will use a default maximum of four keys. Internal nodes have one more child pointer than separator keys. In leaves, the number of key entries matches the number of RID groups, but each group can contain multiple RIDs.
Example B+ tree
Internal node
[20 | 40]
Leaf 1
[5, 12]
Leaf 2
[20, 30]
Leaf 3
[40, 50]
The separator key 20 is the smallest key in the second child, while 40 is the smallest key in the third child. The leaf nodes are also linked together, allowing us to scan keys in sorted order.
For example, if three table rows have the same indexed value, 25, the leaf stores the key 25 only once and keeps all three RIDs in its corresponding RID group. This avoids creating duplicate key entries while still allowing the index to find every matching record.
1keys = {25, 30}
2values = {
3 {rid_a, rid_b, rid_c}, // all records whose key is 25
4 {rid_d} // the record whose key is 30
5}Notice that the internal nodes do not store the actual RIDs in this design. The key-to-RID mapping lives in the leaves. The internal keys are used solely to decide which child to visit during a search.
Defining the node structure
We begin by defining a Node structure inside our BPlusTree class. Each node records whether it is a leaf, its keys, and its relationship with other nodes.
1class BPlusTree
2{
3private:
4 struct Node
5 {
6 explicit Node(bool leaf)
7 : is_leaf(leaf), parent(nullptr), next(nullptr)
8 {
9 }
10
11 bool is_leaf;
12
13 // Keys stored in sorted order.
14 std::vector<int> keys;
15
16 // Leaf nodes: keys[i] maps to one or more RIDs in values[i].
17 std::vector<std::vector<RID>> values;
18
19 // Internal nodes: one more child than separator keys.
20 std::vector<Node *> children;
21
22 Node *parent;
23 Node *next;
24 };
25};The values vector is only used by leaf nodes, whereas children is only used by internal nodes. Keeping these vectors separate makes the different responsibilities of each node explicit.
Each node also has a parent pointer, which helps us propagate splits upwards, and a next pointer, which links leaf nodes together for efficient ordered scans.
We will also maintain ownership of all allocated nodes in a vector ofstd::unique_ptr. This keeps the node objects alive while allowing the tree to use ordinaryNode* pointers for parent-child relationships.
1private:
2 std::vector<std::unique_ptr<Node>> nodes_;
3
4 Node *root_;
5 std::size_t max_keys_;
6
7 Node *create_node(bool is_leaf)
8 {
9 nodes_.push_back(std::make_unique<Node>(is_leaf));
10 return nodes_.back().get();
11 }The constructor initializes an empty tree and sets the maximum number of keys allowed per node. We require at least three keys per node to keep this implementation's splitting behaviour meaningful.
1public:
2 explicit BPlusTree(std::size_t max_keys = 4)
3 : root_(nullptr), max_keys_(max_keys)
4 {
5 if (max_keys < 3)
6 {
7 throw std::invalid_argument(
8 "B+ tree max_keys must be at least 3");
9 }
10 }Finding the correct leaf
Before implementing insertion and search, we need a way to navigate through the tree. Starting at the root, we examine the separator keys and select the child that could contain the target key. We repeat this process until we reach a leaf.
Our internal-node convention is that keys[i] stores the minimum key in children[i + 1]. Therefore, a separator divides the key ranges of two adjacent children.
We use std::upper_bound to find the first separator strictly greater than the target key. The position of that separator is also the index of the child we should visit. If the target equals a separator, we go to the child on its right.
1Node *find_leaf(int key) const
2{
3 Node *current = root_;
4
5 while (!current->is_leaf)
6 {
7 auto it = std::upper_bound(
8 current->keys.begin(),
9 current->keys.end(),
10 key);
11
12 std::size_t index = static_cast<std::size_t>(
13 std::distance(current->keys.begin(), it));
14
15 current = current->children[index];
16 }
17
18 return current;
19}For example, given separator keys [20, 40], a search for 12 visits the first child, a search for 30 visits the second child, and a search for 40 visits the third child. The method returns the leaf where the key should be, whether or not the key actually exists.
Implementing search
Once we have located the appropriate leaf, searching is straightforward. Because leaf keys are sorted, std::lower_bound finds the first key that is greater than or equal to the target. If it matches, we retrieve the vector of RIDs associated with that key. We expose both a search that returns all matching RIDs and a backwards-compatible search that returns just the first RID.
1bool search_all(int key, std::vector<RID> &results) const
2{
3 results.clear();
4
5 if (root_ == nullptr)
6 {
7 return false;
8 }
9
10 Node *leaf = find_leaf(key);
11
12 auto it = std::lower_bound(
13 leaf->keys.begin(),
14 leaf->keys.end(),
15 key);
16
17 if (it == leaf->keys.end() || *it != key)
18 {
19 return false;
20 }
21
22 std::size_t index = static_cast<std::size_t>(
23 std::distance(leaf->keys.begin(), it));
24
25 results = leaf->values[index];
26 return !results.empty();
27}
28
29bool search(int key, RID &rid) const
30{
31 std::vector<RID> results;
32
33 if (!search_all(key, results))
34 {
35 return false;
36 }
37
38 rid = results.front();
39 return true;
40}Both methods return false when the key is missing. search_all returns every RID for a key, while search preserves the simpler interface by returning the first associated RID.
Inserting a key into a leaf
Insertion follows the same navigation process. We first find the leaf where the key belongs. If the key already exists, we append the new RID to its existing RID group. Otherwise, we insert the new key and a group containing its first RID at the same position, keeping the keys sorted.
The return value indicates whether a new distinct key was inserted. If the key already exists, insertion appends the RID and returns false. This does not mean the operation had no effect: the existing key now has one additional RID.
1bool insert(int key, const RID &rid)
2{
3 if (root_ == nullptr)
4 {
5 root_ = create_node(true);
6 root_->keys.push_back(key);
7 root_->values.push_back(std::vector<RID>{rid});
8 return true;
9 }
10
11 Node *leaf = find_leaf(key);
12
13 auto it = std::lower_bound(
14 leaf->keys.begin(),
15 leaf->keys.end(),
16 key);
17
18 std::size_t index = static_cast<std::size_t>(
19 std::distance(leaf->keys.begin(), it));
20
21 // The key exists: append the RID, but no new key was inserted.
22 if (it != leaf->keys.end() && *it == key)
23 {
24 leaf->values[index].push_back(rid);
25 return false;
26 }
27
28 // Insert a new distinct key and its first RID.
29 leaf->keys.insert(it, key);
30 leaf->values.insert(
31 leaf->values.begin() + index,
32 std::vector<RID>{rid});
33
34 if (leaf->keys.size() > max_keys_)
35 {
36 split_leaf(leaf);
37 }
38
39 return true;
40}A leaf can temporarily contain max_keys + 1 keys after an insertion. When that happens, we split it into two leaves. This is the main mechanism that keeps the tree balanced as more keys are inserted.
Splitting a leaf node
To split a leaf, we divide its sorted key entries around the midpoint. Each key moves together with its entire vector of RIDs, so duplicate values stay associated with the correct key. The left leaf keeps the first half, while a new right leaf receives the remaining entries. We then update the leaf links so ordered scans can still move through every leaf.
Splitting a leaf containing five keys
Before
[10, 20, 30, 40, 50]
Left leaf
[10, 20]
Right leaf
[30, 40, 50]
The first key of the right leaf, 30, becomes the separator inserted into the parent. The key remains in the leaf because leaf nodes store the actual searchable entries. If a key has multiple RIDs, its whole RID group moves with it.
1void split_leaf(Node *leaf)
2{
3 Node *right = create_node(true);
4
5 std::size_t middle = leaf->keys.size() / 2;
6
7 right->keys.assign(
8 leaf->keys.begin() + middle,
9 leaf->keys.end());
10
11 right->values.assign(
12 leaf->values.begin() + middle,
13 leaf->values.end());
14
15 leaf->keys.resize(middle);
16 leaf->values.resize(middle);
17
18 // Insert the new leaf into the linked leaf chain.
19 right->next = leaf->next;
20 leaf->next = right;
21
22 right->parent = leaf->parent;
23
24 insert_into_parent(leaf, right);
25}Splitting the leaf is only part of the operation. The parent must also learn that the original leaf now has a new right sibling. We delegate this responsibility to insert_into_parent.
Maintaining separator keys
Whenever the children of an internal node change, its separator keys must be updated. Instead of manually calculating each separator during every split, we use a helper to rebuild them from the children.
The min_key helper descends through the leftmost child until it reaches a leaf. The first key in that leaf is the minimum key in the entire subtree.
1int min_key(Node *node) const
2{
3 while (!node->is_leaf)
4 {
5 node = node->children.front();
6 }
7
8 return node->keys.front();
9}An internal node with children [C0, C1, C2] needs two separator keys: the minimum key in C1 and the minimum key in C2. There is no separator for C0 because it is the leftmost child.
1void rebuild_keys(Node *node)
2{
3 node->keys.clear();
4
5 if (node->is_leaf)
6 {
7 return;
8 }
9
10 for (std::size_t i = 1;
11 i < node->children.size();
12 ++i)
13 {
14 node->keys.push_back(min_key(node->children[i]));
15 }
16}This helper keeps the relationship between children and separators consistent. It also makes the splitting logic easier to understand, because we can rearrange child pointers first and then reconstruct the separator keys.
Inserting a split node into its parent
After a leaf splits, we insert the new right sibling immediately after the original leaf in the parent's child vector. We then rebuild the parent's separator keys.
There are two cases to handle. If the split node was the root, we create a new internal root with the two resulting nodes as its children. Otherwise, we insert the right sibling into the existing parent.
1void insert_into_parent(Node *left, Node *right)
2{
3 if (left->parent == nullptr)
4 {
5 Node *new_root = create_node(false);
6
7 new_root->children.push_back(left);
8 new_root->children.push_back(right);
9
10 left->parent = new_root;
11 right->parent = new_root;
12
13 rebuild_keys(new_root);
14 root_ = new_root;
15 return;
16 }
17
18 Node *parent = left->parent;
19
20 auto it = std::find(
21 parent->children.begin(),
22 parent->children.end(),
23 left);
24
25 std::size_t index = static_cast<std::size_t>(
26 std::distance(parent->children.begin(), it));
27
28 parent->children.insert(
29 parent->children.begin() + index + 1,
30 right);
31
32 right->parent = parent;
33
34 rebuild_keys(parent);
35
36 if (parent->keys.size() > max_keys_)
37 {
38 split_internal(parent);
39 }
40}Notice that inserting a sibling can cause the parent itself to overflow. If that happens, we must split the internal node as well. This is why the process can propagate from a leaf towards the root.
Splitting an internal node
Splitting an internal node differs from splitting a leaf. Internal nodes store child pointers rather than record RIDs, so we divide the children into two groups. The right half is moved into a new internal node, and each moved child's parent pointer must be updated.
1void split_internal(Node *node)
2{
3 Node *right = create_node(false);
4
5 std::size_t middle = node->children.size() / 2;
6
7 right->children.assign(
8 node->children.begin() + middle,
9 node->children.end());
10
11 node->children.resize(middle);
12
13 for (Node *child : right->children)
14 {
15 child->parent = right;
16 }
17
18 right->parent = node->parent;
19
20 rebuild_keys(node);
21 rebuild_keys(right);
22
23 // The parent may overflow too, so splitting can propagate upwards.
24 insert_into_parent(node, right);
25}Once the child pointers have been redistributed, we rebuild the separator keys for both internal nodes. We then insert the new right node into the parent using the same helper as before. If the original node was the root, this creates a new root; otherwise, the split may continue upwards.
Putting it all together
We now have the core operations needed for an in-memory B+ tree: navigating to a leaf, searching for one or all RIDs associated with a key, inserting keys and RIDs, rebuilding separator keys, and splitting overflowing nodes. Duplicate RIDs are grouped under one distinct key entry, so they do not by themselves cause a leaf split.
The key idea is that every split preserves the ordering of the keys and updates the parent-child relationships. Leaf splits also maintain the linked list used for ordered scans. Internal splits can propagate upwards until the tree has enough room or a new root is created.
This implementation is an in-memory index: it does not yet persist tree nodes to disk or integrate the index with the buffer pool. Those would be natural next steps when extending the database engine.
Integrating Indexes with the Table Heap
A B+ tree maps indexed values to record identifiers (RIDs), but creating the tree alone does not keep it synchronized with the table. If rows are inserted into the table without updating the index, lookups can return incomplete results. We therefore connect the index to TableHeap, which is responsible for inserting and retrieving table records.
The table heap exposes anadd_index() method. It registers an integer column as an index and takes care of both existing rows and future inserts. The caller supplies the B+ tree, the table schema, and the column position to index.
1bool add_index(
2 BPlusTree &index,
3 const Schema &schema,
4 std::size_t column_index);Storing registered index metadata
The table heap needs to remember which indexes it is responsible for maintaining. Rather than storing only a B+ tree pointer, it keeps a small metadata structure calledIndexInfo for each registered index:
1private:
2 struct IndexInfo
3 {
4 BPlusTree *index;
5 Schema schema;
6 std::size_t column_index;
7 };
8
9 BufferPoolManager &bpm_;
10 std::vector<PageId> pages;
11 std::vector<IndexInfo> indexes_;Each field has a specific purpose:
indexis a pointer to the B+ tree that receives the key-to-RID entries. It is a non-owning pointer: the table heap does not create or destroy the tree, so the caller must keep it alive.schemais a copy of the table schema. It lets the table heap interpret a tuple and extract the indexed column's value later, when a new tuple is inserted.column_indexidentifies which column in that schema is indexed. The same tuple can therefore be read using the correct column for each registered index.
indexes_ is a vector of these IndexInfoobjects. It allows one table heap to maintain multiple indexes, potentially on different columns. Whenever a tuple is inserted, the table heap iterates through this vector and updates every registered B+ tree. Keeping the metadata together also meansinsert_tuple()does not need the caller to pass the schema or column position again.
Validating and registering an index
Before registering the index, we validate the column position and require its type to be INTEGER. The index must also be empty so that backfilling does not mix old entries with unrelated data. We reject registering the same index object more than once.
1if (column_index >= schema.column_count() ||
2 schema.column(column_index).type() != TypeId::INTEGER ||
3 !index.empty())
4{
5 return false;
6}
7
8const auto existing = std::find_if(
9 indexes_.begin(), indexes_.end(),
10 [&index](const IndexInfo &info) {
11 return info.index == &index;
12 });
13
14if (existing != indexes_.end())
15{
16 return false;
17}Backfilling rows that already exist
An index may be registered after the table already contains rows. To handle this, add_index()scans the table to obtain its RIDs, fetches each corresponding tuple, extracts the indexed integer value, and inserts the key-to-RID mapping into the B+ tree. This initial pass is called backfilling.
1for (const RID &rid : scan())
2{
3 Tuple tuple;
4
5 if (!get_tuple(rid, tuple))
6 {
7 return false;
8 }
9
10 const int key =
11 tuple.get_value(schema, column_index).as_int();
12
13 index.insert(key, rid);
14}
15
16indexes_.push_back(
17 IndexInfo{&index, schema, column_index});Once backfilling succeeds, the table heap stores the index pointer, a copy of the schema, and the indexed column position. The table heap does not own the B+ tree, so the index object must remain alive for as long as the table heap may use it.
Keeping the index up to date on inserts
Registering an index is only half the work. Every later successful tuple insertion must also add its key and RID to each registered index. After the table page accepts the tuple, the table heap extracts the indexed value and inserts the mapping into the B+ tree. The same maintenance step is used whether the tuple fits on an existing page or requires a newly allocated page.
1for (const IndexInfo &info : indexes_)
2{
3 const int key = tuple.get_value(
4 info.schema, info.column_index).as_int();
5
6 info.index->insert(key, rid);
7}The B+ tree handles duplicate values by keeping one distinct key entry with a collection of RIDs. This means multiple table rows can share the same indexed value without losing any matching records.
This integration currently supports integer indexes and successful tuple inserts. Updates and deletes do not yet maintain index entries, and the B+ tree itself remains in memory rather than being persisted as database pages. Those limitations are important: callers should not treat this index as durable or automatically synchronized with operations that the table heap does not yet support.
Querying Through an Index
The B+ tree lets us find the record identifiers (RIDs) associated with a key, but it does not store the actual table records. To use the index during query execution, we need to connect the index to the table heap. This is the role of theIndexScanExecutor: it looks up matching RIDs in the B+ tree and uses them to fetch tuples from the table.
Making index scans part of the executor pipeline
In Part 2, we introduced a commonExecutor interface with init() andnext(). By implementing this interface, an index scan can be used anywhere another executor is expected, including as the child of a projection executor.
1class IndexScanExecutor : public Executor
2{
3public:
4 IndexScanExecutor(
5 TableHeap &table_heap,
6 const BPlusTree &index,
7 int key);
8
9 void init() override;
10 bool next(Tuple &tuple, RID &rid) override;
11
12private:
13 TableHeap &table_heap_;
14 const BPlusTree &index_;
15 int key_;
16
17 std::vector<RID> rids_;
18 std::size_t next_rid_index_ = 0;
19};The executor keeps references to the table heap and index, the lookup key, the matching RIDs, and an offset indicating which RID should be processed next. This allows it to produce tuples incrementally instead of returning the entire result set at once.
Initializing the index scan
During initialization, the executor clears any previous results and calls search_all()on the B+ tree. Unlike search(), which returns only the first RID, search_all()retrieves every RID associated with the key. This matters for non-unique indexes, where multiple records can share the same indexed value.
1void IndexScanExecutor::init()
2{
3 rids_.clear();
4 index_.search_all(key_, rids_);
5 next_rid_index_ = 0;
6}Resetting next_rid_index_to zero makes the executor reusable: callinginit() again starts from the first matching RID.
Fetching tuples one at a time
Each call to next()processes RIDs until it finds a tuple that can be fetched. The executor calls TableHeap::get_tuple()for each candidate. If a RID no longer refers to a retrievable tuple, it skips that entry and continues with the next one.
1bool IndexScanExecutor::next(Tuple &tuple, RID &rid)
2{
3 while (next_rid_index_ < rids_.size())
4 {
5 RID current_rid = rids_[next_rid_index_++];
6
7 Tuple current_tuple;
8
9 if (!table_heap_.get_tuple(current_rid, current_tuple))
10 {
11 continue;
12 }
13
14 tuple = current_tuple;
15 rid = current_rid;
16 return true;
17 }
18
19 return false;
20}A successful call returns one tuple and its RID. Once all candidate RIDs have been examined, next()returns false to signal that the scan is exhausted. Unlike a sequential scan, this executor does not evaluate a predicate for every row: the B+ tree lookup has already selected entries matching the requested equality key.
Composing an index scan with projection
Because IndexScanExecutorimplements the shared interface, it can be passed directly to aProjectionExecutor. For example, an index lookup for user ID 2 can retrieve the row, while projection selects only the age column.
1IndexScanExecutor index_scan(table, index, 2);
2
3ProjectionExecutor projection(
4 index_scan,
5 schema,
6 {"age"});
7
8projection.init();
9
10Tuple tuple;
11RID rid;
12
13while (projection.next(tuple, rid))
14{
15 int age = tuple.get_value(
16 projection.output_schema(), 0).as_int();
17
18 std::cout << "age=" << age << '\n';
19}Initializing the projection also initializes its child index scan. Each call to projection.next()asks the child for its next tuple, applies the column selection, and returns the projected tuple. The projection executor does not need to know whether its input came from a sequential scan or an index scan; both follow the same executor contract.
Sequential scan versus index scan
Both executors ultimately retrieve tuples from the table heap, but they identify candidate records differently. A sequential scan walks through the table's RIDs and evaluates an expression against each tuple. An index scan uses the B+ tree to find RIDs for a specific key, then fetches those records. For selective equality lookups, this avoids examining every row in the table.
Putting it all together
We now have two ways to produce tuples: a sequential scan that examines table records, and an index scan that uses a B+ tree to find candidate RIDs. Both implement the same executor interface, so operators such as projection can consume either one. The B+ tree handles key-to-RID lookup, the table heap retrieves the actual tuple, and the executor connects these components into a query pipeline.