Link Search Menu Expand Document

Save this note as PDF

Introduction

In the previous notes, we went over different file and record representations for data storage. This week, we will introduce index which is a data structure that operates on top of the data files and helps speed up reads on a specific key. You can think of data files as the actual content of a book and a index as the table of content for fast lookup. We use indexes to make queries run faster, especially those that are run frequently. Consider a web application that looks up the record for a user in a Users table based on the username during the login process. An index on the username column will make login faster by quickly finding the row of the user trying to log in. In this course note, we will learn about B+ trees, which is a specific type of index. Here is an example of what a B+ tree looks like:

image

Properties

  • The number d is the order of a B+ tree. Each node (with the exception of the root node) must have d ≤ x ≤ 2d entries assuming no deletes happen (it’s possible for leaf nodes to end up with < d entries if you delete data). The entries within each node must be sorted.

  • In between each entry of an inner node, there is a pointer to a child node. Since there are at most 2d entries in a node, inner nodes may have at most 2d+1 child pointers. This is also called the tree’s fanout.

  • The keys in the children to the left of an entry must be less than the entry while the keys in the children to the right must be greater than or equal to the entry.

  • All leaves are at the same depth and have between d and 2d entries (i.e., at least half full)

For example, here is a node of an order d=2 tree:

image

Note that the node satisfies the order requirement, also known as the occupancy invariant (d ≤ x ≤ 2d) because d=2 and this node has 3 entries which satisfies 2 ≤ x ≤ 4.

  • Because of the sorted and children property, we can traverse the tree down to the leaf to find our desired record. This is similar to BSTs (Binary Search Trees).

  • Every root to leaf path has the same number of edges - this is the height of the tree. In this sense, B+ trees are always balanced. In other words, a B+ tree with just the root node has height 0.

  • Only the leaf nodes contain records (or pointers to records - this will be explained later). The inner nodes (which are the non-leaf nodes) do not contain the actual records.

For example, here is an order d=1 tree:

image

Insertion

To insert an entry into the B+ tree, follow this procedure:

  1. Find the leaf node L in which you will insert your value. You can do this by traversing down the tree. Add the key and the record to the leaf node in order.

  2. If L overflows (L has more than 2d entries)

    1. Split into L_1 and L_2. Keep d entries in L_1 (this means d+1 entries will go in L_2).

    2. If L was a leaf node, COPY L_2’s first entry into the parent. If L was not a leaf node, MOVE L_2’s first entry into the parent.

    3. Adjust pointers.

  3. If the parent overflows, then recurse on it by doing step 2 on the parent. (This is the only case that increases the tree height)

Note: we want to COPY leaf node data into the parent so that we don’t lose the data in the leaf node. Remember that every key that is in the table that the index is built on must be in the leaf nodes! Being in a inner node does not mean that key is actually still in the table. On the other hand, we can MOVE inner node data into parent nodes because the inner node does not contain the actual data, they are just a reference of which way to search when traversing the tree.

Let’s take a look at an example to better understand this procedure! We start with the following order d=1 tree:

image

Let’s insert 19 into our tree. When we insert 19, we see that there is space in the leaf node with 17:

image

Now let’s insert 21 into our tree. When we insert 21, it causes one of the leaf nodes to overflow. Therefore, we split this leaf node into two leaf nodes as shown below:

image

L_1 is the leaf node with 17, and L_2 is the leaf node with 19 and 21.

Since we split a leaf node, we will COPY L_2’s first entry up to the parent and adjust pointers. We also sort the entries of the parent to get:

image

Let’s do one more insertion. This time we will insert 36. When we insert 36, the leaf overflows so we will do the same procedure as when we inserted 21 to get:

image

Notice that now the parent node overflowed, so now we must recurse. We will split the parent node to get:

image

L_1 is the inner node with 19, and L_2 is inner the node with 27 and 32.*

Since it was an inner node that overflowed, we will MOVE L_2’s first entry up to the parent and adjust pointers to get:

image

Lastly, here are a couple clarifying notes about insertion into B+ Trees:

  • Generally, B+ tree nodes have a minimum of d entries and a maximum of 2d entries. In other words, if the nodes in the tree satisfy this invariant before insertion (which they generally will), then after insertion, they will continue to satisfy it.

  • Insertion overflow of the node occurs when it contains more than 2d entries.

Deletion

To delete a value, just find the appropriate leaf and delete the unwanted value from that leaf. That’s all there is to it. (Yes, technically we could end up violating some of the invariants of a B+ tree. That’s okay because in practice we get way more insertions than deletions so something will quickly replace whatever we delete.)

Reminder: We never delete inner node keys because they are only there for search and not to hold data.

Storing Records

Up until now, we have not discussed how the records are actually stored in the leaves. Let’s take a look at that now. There are three ways of storing records in leaves:

  • Alternative 1: By Value

    In the Alternative 1 scheme, the leaf pages are the data pages. Rather than containing pointers to records, the leaf pages contain the records themselves.

    Points Name
    2 MEM
    3 LAK
    5 BOS
    7 MIL
    20 BKL
    24 GSW

    image

    While the Alternative 1 Scheme is perhaps the easiest implementation, it has a significant limitation: if all we have is the Alternative 1 Scheme, we cannot support multiple indexes built on the same file (in the example above we cannot support a secondary index on ‘name’. Instead we would have to duplicate the file and build a new Alternative 1 index on top of that file.

  • Alternative 2: By Reference

    In the Alternative 2 scheme, the leaf pages hold pointers to the corresponding records.

    Points Name
    2 MEM
    3 LAK
    5 BOS
    7 MIL
    20 BKL
    24 GSW

    image

    Notation Clarification: In the diagram above, the leafs contain (Key, RecordID) pairs where the RecordID is [PageNum, RecordNum].

    Indexing by reference enables us to have multiple indexes on the same file because the actual data can lie in any order on disk.

  • Alternative 3: By List of References

    In the Alternative 3 scheme, the leaf pages hold lists of pointers to the corresponding records. This is more compact than Alternative 2 when there are multiple records with the same leaf node entry. Each leaf now contains (Key, List of RecordID) pairs.

    Points Name
    2 MEM
    2 LAK
    2 BOS
    7 MIL
    7 BKL
    50 GSW

    image

Clustering

Now that we’ve discussed how records are stored in the leaf nodes, we will also discuss how data on the data pages are organized. Clustered/unclustered refers to how the data pages are structured. Because the leaf pages are the actual data pages for Alternative 1 and keys are sorted on the index leaf pages, Alternative 1 indices are clustered by default. Therefore, unclustering only applies to Alternative 2 or 3.

  • Unclustered

    In an unclustered index, the data pages are complete chaos. Thus, odds are that you’re going to have to read a separate page for each of the records you want. For instance, consider this illustration:

    image

    In the figure above, if we want to read records with 12 and 24, then we would have to read in each of the data pages they point to in order to retrieve all the records associated with these keys.

  • Clustered

    In a clustered index, the data pages are sorted on the same index on which you’ve built your B+ tree. This does not mean that the data pages are sorted exactly, just that keys are roughly in the same order as data. The difference in I/O cost therefore comes from caching, where two records with close keys will likely be in the same page, so the second one can be read from the cached page. Thus, you typically just need to read one page to get all the records that have a common / similar key. For instance, consider this illustration:

    image

    In the figure above, we can read records with 7 and 12 by reading 2 pages. If we do sequential reads of the leaf node values, the data page is largely the same. In conclusion,

  • UNCLUSTERED = ~1 I/O per record.

  • CLUSTERED = ~1 I/O per page of records.

  • Clustered vs. Unclustered Indexes

    While clustered indexes can be more efficient for range searches and offer potential locality benefits during sequential disk access and prefetching, etc, they are usually more expensive to maintain than unclustered indexes. For example, the data file can become less clustered with more insertions coming in and, therefore, require periodical sorting of the file.

Counting IO’s

Here’s the general procedure. It’s a good thing to write on your cheat sheet:

  1. Read the appropriate root-to-leaf path.

  2. Read the appropriate data page(s). If we need to read multiple pages, we will allot a read IO for each page. In addition, we account for clustering for Alt. 2 or 3 (see below.)

  3. Write data page, if you want to modify it. Again, if we want to do a write that spans multiple data pages, we will need to allot a write IO for each page.

  4. Update index page(s).

Let’s look at an example. See the following Alternative 2 Unclustered B+ tree:

image

We want to delete the only 11-year-old from our database. How many I/Os will it take?

  • One I/O for each of the 2 relevant index pages on the roof-to-leaf path (an index page is an inner node or a leaf node).

  • One I/O to read the data page where the 11-year-old’s record is. Once it’s in memory we can delete the record from the page.

  • One I/O to write the modified data page back to disk.

  • Now that there are no more 11-year-olds in our database we should remove the key "11" from the leaf page of our B+ tree, which we already read in Step 1. We do so, and then it takes one I/O to write the modified leaf page to disk.

  • Thus, the total cost to delete the record was 5 I/Os.

Bulk Loading

The insertion procedure we discussed before is great for making additions to an existing B+ tree. If we want to construct a B+ tree from scratch, however, we can do better. This is because if we use the insertion procedure we would have to traverse the tree each time we want to insert something new; regular insertions into random data pages also lead to poor cache efficiency and poor utilization of the leaf pages as they are typically half-empty. Instead, we will use bulkloading:

  1. Sort the data on the key the index will be built on.

  2. Fill leaf pages until some fill factor f. Note that fill factor only applies to leaf nodes. For inner nodes, we still follow the same rule to insert until they are full.

  3. Add a pointer from parent to leaf page. If the parent overflows, we will follow a procedure similar to insertion. We will split the parent into two nodes:

    1. Keep d entries in L_1 (this means d+1 entries will go in L_2).

    2. Since a parent node overflowed, we will MOVE L_2’s first entry into the parent.

  4. Adjust pointers.

Let’s look at an example. Let’s say our fill factor is 3/4 and we want to insert 1, … , 20 into an order d=2 tree. We will start by filling a leaf page until our fill factor:

image

We have filled a leaf node to the fill factor of 3/4 and added a pointer from the parent node to the leaf node. Let’s continue filling:

image

In the figure above, we see that the parent node has overflowed. We will split the parent node into two nodes and create a new parent:

image

As you can see from the above example, indexes built from bulkloading always start off clustered because the underlying data is sorted on the key. To maintain clustering, we can choose the fill factor depending on future insertion patterns.

Past Exam Problems

Sp22 Final Q3: The Power of B+ Trees (21 points)

(a) (3 pt) Which of the following choices are true statements? Mark all that apply.

  • A. While traversing a B+ Tree, we need to do a binary search across all nodes in a layer to figure out which node to take to the next layer.
  • B. When a leaf node overflows when inserting into an Alt. 3 B+ Tree, we copy up the middle entry (out of 2d + 1 entries).
  • C. We can always assume clustered indexes incur 1 I/O per page of records regardless of caching or not.
  • D. Bulkloading allows us to make use of temporal locality.
  • E. The main usage of B+ Trees is to sort the records.
  • F. None of the above.
Solution

B and D.

(b) The Technoking

Due to current events, Bob wants to analyze Elon Musk’s Twitter tweets to see if he can derive any insights. Bob has the following table tweets containing information about Elon Musk’s tweets:

CREATE TABLE tweets {
    tid INTEGER PRIMARY KEY,  // the tweet id
    subject TEXT,             // string that summarizes the tweet's topic
    time, INTEGER,            // Unix timestamp of this tweet
    likes INTEGER,            // number of likes
    retweets INTEGER,         // number of retweets
    spam BOOLEAN              // whether Twitter marked this as spam or not
}

We have one index on this table:

Index A:

  • Alt. 2, clustered B+ Tree on (subject, time) with h = 2, d = 4
  • All leaf nodes are full.
  • Each data page stores 20 records
  • The index was built on a file completely sorted on key (subject, time)

Additional Assumptions:

  • The tweets table has exactly 400 data pages

i. (2 pt) Bob wants to find Elon’s Tweet where he first thought about purchasing Twitter. Assuming we are given subject = “Buying Twitter” and the time this tweet was posted, what is the minimum I/O cost to execute this query?

Solution

4

2 I/Os (inner node) + 1 I/O (leaf node) + 1 I/O (data page) = 4 I/Os.

ii. (2 pt) While sitting in Soda Hall, Bob overhears a conversation saying Elon Musk’s latest tweet went viral and is now his most liked tweet ever. Curious, Bob decides to write a query to find this tweet. What is the minimum I/O cost to execute this query?

Solution

400 I/Os

We don’t have an index built on likes, so we can only do a full scan.

iii. (3 pt) Bob wants to write a query to find all of Elon’s Tweets with the subject “Tesla”. Assume Bob’s data includes 80 tweets with the subject “Tesla” at unique timestamps. What is the worst case I/O cost of Bob’s query? You must use the index (assume the index is used properly and no extra I/Os incur). Assume the query is run independently of previous parts.

Solution

18

We are told there are 80 tweets with the subject “Tesla” at unique timestamps. This implies we need to check 80 keys. At the worst case, the key with subject = “Tesla” is the last entry in the leaf node it first occurs at. This means in the worst case, the number of leaf nodes we need to read is 1 + ceil(79/8) = 11. Similarly, in the worst case the first record is the 20th record on a data page. Because our B+ Tree is clustered, we need to check 1 + ceil(79/20) = 5 data pages. Thus, our total number of I/Os is 2 (inner nodes) + 11 (leaf nodes) + 5 (data pages) = 18 I/Os.

(c) B+ Trees for Machine Learning

In machine learning, the kNN (k nearest neighbor) algorithm is an algorithm used to solve classification problems. The algorithm essentially works by:

  1. Given a sample point, find the distance between the sample point and all other points. Assume distance is calculated using Euclidean distance (definition of Euclidean distance is irrelevant to this question).
  2. We take the k-closest neighbors and aggregate their labels. For example, neighbor 1 is class 1, neighbor 2 is class 1, neighbor 3 is class 2, neighbor 4 is class 3. We then have 2 class 1’s, 1 class 2 and 1 class 3.
  3. Predict our sample point as the class with the most neighbors. Using our example from above, our sample point would be labeled as class 1.

We will use a B+ Tree to speed up the finding k-closest neighbors step for a sample point sample. Assume we are given the following lines of code:

/** Returns the Euclidean distance between point1 and point2 */
private float distance(Point point1, Point point2) {
    // implementation hidden
}

/** Creates and adds a record corresponding to `point` into our B+ Tree.
 * The record is added to our B+ Tree using `key`.
 */
private void createAddRecord(<some type> key, Point point) {
    // implementation hidden
}

/** Fill up a B+ Tree with keys to make finding the K-nearest neighbors of `sample` faster.
 * `sample` is the sample point we want to classify
 * `points` is an array of all other points not including `sample`
 */
private void fillUpBPlusTree(Point sample, Point[] points) {
    for (Point point : points) {
        // QUESTION 1
        // QUESTION 2
    }
}

i. (2 pt) What line of code should go in the line marked as // QUESTION 1? Only answer with a single line of code and correct Java syntax will be given credit.

Solution

float key = distance(sample, point);

ii. (2 pt) What line of code should go in the line marked as // QUESTION 2? Only answer with a single line of code and correct Java syntax will be given credit.

Solution

createAddRecord(key, point);

iii. (3 pt) Assume we built our B+ Tree correctly. In less than 3 sentences, explain how we would use our B+ tree to find the K closest neighbors to sample. Answers longer than 3 sentences will not be given credit.

Solution

Mentions using a range scan from 0/leftmost leaf node and scanning to the right until k keys have been found. Can only scan from left to right as L1 norm (Euclidean Distance) is always greater than or equal to 0. Answers that mention reading k leaf nodes are given partial credit as it is not necessarily true we need to read k leaf nodes.

iv. (4 pt) In what situations is our B+ Tree helpful when running kNN for sample?

  • A. We want to get rid of outliers from the graph.
  • B. We want to find neighbors within a range of distance from the sample point.
  • C. We want to rerun kNN multiple times.
  • D. We want to run kNN for a point which is not sample.
  • E. None of the above.
Solution

A, B, and C.

Fa21 Midterm 1 Q4: B+ Trees (28 points)

Let’s build indices! Please keep in mind that some questions have multiple parts so budget your time accordingly.

(a) (2 pt) Which of the following are true? Select all that apply. There may be more than one correct answer.

  • A. B+ Trees will speed up queries by reducing the big O runtime of searching for records on a page in memory.
  • B. B+ Trees can possibly increase the I/O cost of a query.
  • C. B+ Trees can speed up queries by reducing the number of data pages read into memory.
  • D. B+ Trees can only be built on columns with type INTEGER or FLOAT.
  • E. None of the above.
Solution

B and C.

  • A: B+ Trees can improve the number of I/Os incurred but don’t affect the in-memory big O runtime.
  • B: One example: if we’re searching for a single record and it’s on the very first page, reading in nodes in the B+ Tree will be more costly. In general, indices will help but not always!
  • C: Instead of searching through all the pages in the heapfile for a record or range of records, we can use a B+ Tree to find the corresponding page more quickly, saving I/Os.
  • D: We can build indices on any type of column.

(b) B+ Tree Searches and Inserts (3 points)

Given the tree below, answer the following questions.

B+ tree with root (1, 5), edges (c), (d), (e), and leaves (-5, a), (1, b), (5, 8)

i. (1 pt) We want to search for key 3. Which of the following edges would we traverse?

  • c
  • d
  • e
  • None of the above
Solution

d. Key 3 is between 1 and 5 so we search the middle child.

ii. (1 pt) We want to search for key 10. Which of the following edges would we traverse?

  • c
  • d
  • e
  • None of the above
Solution

e. Key 10 is larger than 5 so we search the rightmost child.

iii. (1 pt) We want to insert key 4. Where would it be inserted into?

  • a
  • b
  • None of the above
Solution

b. Key 4 is between 1 and 5 so we insert into the middle child.

(c) (1 pt) Is the following B+ Tree possible assuming no deletions and no rebalancing?

B+ tree for part (c)

  • Yes
  • No

(d) (1 pt) Briefly justify your answer above in 1 sentence.

Solution

(c) No. (d) B+ trees are balanced and grow from the root.

(e) (1 pt) Is the following B+ Tree possible assuming no deletions and no rebalancing?

B+ tree for part (e)

  • Yes
  • No

(f) (1 pt) Briefly justify your answer above in 1 sentence.

Solution

(e) No. (f) Key 10 could not have ended up in the inner/root node unless it was copied up from a leaf node.

(g) (1 pt)

Order 1 B+ tree with root (5, 10) and leaves (-1, 3), (5), (10, 12)

Given the above order 1 B+ Tree, what is the result after inserting 15?

A.

Option A

B.

Option B

C.

Option C

D.

Option D

Solution

D

15 is inserted into the rightmost child, causing it to overflow and split. 12, the middle key, is then copied up to the root node which also overflows and splits. 10, the middle key of the root, is pushed up to be the new root.

(h) (1 pt) Give an example of a key we insert to increase the height of the order 1 tree below? Write N/A if it is not possible to increase the height of the tree in one insertion. Assume that no duplicates are allowed in this B+ Tree.

Order 1 B+ tree with root (3, 10) and leaves (-1), (3, 8), (10)

Solution

Any key in [4, 9] will cause the middle child to split, causing a key to be copied up to the root. This causes the root to also split.

(i) Lakshya’s Jokes (15 points)

Lakshya does stand up comedy in his free time and has a table to store all of his jokes.

CREATE TABLE jokes (
    joke_id INTEGER PRIMARY KEY,
    topic TEXT,
    description TEXT,
    rating INTEGER
    num_laughs INTEGER
);

Since his table is getting very large, he decides to build the two following indices to speed up his queries.

Index A:

  • Alternative 1 B+ Tree on column topic
  • Order 3 (d=3)
  • Height 4

Index B:

  • Alternative 2 unclustered B+ Tree on column rating
  • Order 2 (d=2)
  • Height 3

Assumptions:

  • There are 5 records where topic=’parrots’
  • There are 15 records where rating > 80
  • There are 8 records where topic=’databases’
  • The root is NOT cached in memory.
  • The buffer manager starts empty at the start of each query.
  • The table contains a total of 100 data pages.
  • One data page can store up to 10 records.
  • Assume the leaf nodes are full.

Answer the following questions. Please pay attention to whether we’re looking for best case (minimum I/O cost) or worst case.

i. (1 pt) Do we need to duplicate the data pages between Index A and Index B?

  • Yes
  • No
Solution

No. Index A needs to be sorted, but B does not need to be sorted because it’s unclustered.

ii. (2 pt) What is the minimum I/O cost for the following query?

SELECT * FROM jokes;
Solution

100. Read all data pages. Credit also given for 104.

iii. (2 pt) What is the minimum I/O cost for the following query?

SELECT * FROM jokes WHERE topic='parrots';
Solution

5

4 I/Os to read the inner nodes + 1 I/O to read the leaf node which contains the data in an Alt 1 tree. In the best/minimum cost case, all the data will fit onto one leaf page since we assume 5 matches.

iv. (1 pt) Is the above query sped up by either index?

  • Yes
  • No
Solution

Yes

v. (2 pt) What is the worst case I/O cost for the following query?

SELECT * FROM jokes WHERE rating > 80;
Solution

23

3 I/Os to read the inner nodes. In the worst case, the 15 matches will be split across 5 leaf pages so 5 I/Os to read the leaf nodes. Since it’s an unclustered index, 1 I/O per matching record. In the worst case, the 15 matching records will each be on a different page.

vi. (1 pt) Is the above query sped up by either index?

  • Yes
  • No
Solution

Yes

vii. (2 pt) What is the worst case I/O cost for the following query?

SELECT * FROM jokes WHERE num_laughs > 10 AND topic='databases';
Solution

6

4 I/Os to read the inner nodes. In the worst case, the 8 matching records will be split across 2 data pages so 2 I/Os to read these two leaf pages.

viii. (1 pt) Is the above query sped up by either index?

  • Yes
  • No
Solution

Yes

ix. (2 pt) What is the minimum I/O cost for the following query?

SELECT * FROM jokes WHERE num_laughs > 10 OR topic='databases';
Solution

100

We can’t use Index A to help us with this query. We need to check all records since the predicate contains an OR. Read all data pages. Credit also given for 104.

x. (1 pt) Is the above query sped up by either index?

  • Yes
  • No
Solution

No

(j) (2 pt) Suppose we want a tree of height 2. How many records would we need to insert when bulk loading with a fill factor of 3/4 given d=4?

Solution

55

After 6 insertions, we fill up the initial leaf node to the fill factor. On the 7th insertion, it splits and we get a height 1 tree. After a total of 54 insertions, we have 9 leaf nodes filled to the fill factor. On the 55th insertion, the leaf node splits and the height increases to 2.

Fa21 Final Q4: B+ Trees (21 points)

(a) (2 pt) Which of the following are true? Select all that apply. There may be more than one correct answer.

  • A. Bulk-loading a B+ tree with fill factor > 0.5 can result in a tree with more nodes than we would get by following the standard insertion algorithm taught in class.
  • B. Assuming records can fit on one page, looking up a single record using an alternative 2 index will always cost more I/Os than lookups that utilize an alternative 1 index
  • C. B+ trees can have composite primary keys of different data types (e.g. (Integer, String))
  • D. An alternative-3 index will always be at least as cost-efficient for lookups as an alternative-2 index in terms of I/Os.
  • E. None of the above.
Solution

A, C, and D.

(b) Tree Examination

Under the rules taught in this course, decide if the following B+ Trees are possible assuming no deletions and no rebalancing. Remember that strings are sorted lexicographically ‘a’ being the lowest value to ‘z’ being the greatest.

i. (1 pt)

Tree i

  • YES
  • NO
Solution

NO. The 3 cannot be on the left node.

ii. (1 pt)

Tree ii

  • YES
  • NO
Solution

NO. The root node values aren’t in the leaf nodes.

iii. (1 pt)

Tree iii

  • YES
  • NO
Solution

NO (‘oj’ cannot end up in the center node). In a split, the right node would get 2 keys, and so ‘oj’ would have to end up in the rightmost node, not the center node.

iv. (1 pt)

Tree iv

  • YES
  • NO
Solution

YES

v. (1 pt)

Tree v

  • YES
  • NO
Solution

YES, this is possible – the left root key is in the middle node and the right root key is in the right node. Try the insertion pattern (‘b’, 9), (‘f’, 7), (‘g’, 13), (‘x’, 12), (‘e’, 7) to construct this tree.

vi. (2 pt) Consider the following valid B+ tree which may have had any number of prior deletions and insertions. How many insertions will it take to change the height of the tree, at minimum?

Tree vi

Solution

1: insert any key between ‘limeade’ and ‘sprite’ lexicographically.

vii. (2 pt) Consider the following valid B+ tree which may have had any number of prior deletions and insertions. What is the maximum number of insertions we can put in without changing the height of the tree?

Tree vii

Solution

4: the number of keys we can hold in a tree of height 1 with order 1 is 6, and there are 2 entries here.

(c) (2 pt) Assume we have an alternative 2 B+ tree of height 4 and that the index is cached (in memory). Assume that all records can fit on a page. How many I/Os will it take to lookup and fetch a single record?

Solution

1: the index is cached so we just need to go to disk to fetch the record needed.

(d) (2 pt) Assume we have an alternative 3 B+ tree of height 5. Assume that all records can fit on a page. How many I/Os will it take to lookup and fetch a single record?

Solution

7: we need to read in the root node, then traverse 5 more nodes to get from root to leaf, and then we need to fetch the data page from disk.

(e) School Queries

A school decides to create a database to keep the academic records of all former and current students.

CREATE TABLE students (
    sid INTEGER PRIMARY KEY,
    name TEXT,
    major TEXT,
    gpa FLOAT,
    is_enrolled BOOLEAN
);

This table is getting to be somewhat large, and so they build some indexes to speed up the queries they’ll be performing.

Index A:

  • Alternative 2 unclustered B+ Tree on column gpa
  • Order 5 (d=5)
  • Height 3

Index B:

  • Alternative 3 clustered B+ Tree on column major
  • Order 3 (d=3)
  • Height 2

Assumptions:

  • There are 80 records where gpa <= 2.0
  • There are 20 records where gpa == 4.0
  • There are 20 records where major = ‘computer science’
  • The root is NOT cached in memory.
  • The buffer manager starts empty at the start of each query.
  • The table contains a total of 100 data pages.
  • There also exists a page directory for the table, with 100 entries per page.
  • One data page can store up to 10 records.
  • Assume the leaf nodes are full.

Answer the following questions. Please pay attention to whether we’re looking for best case (minimum I/O cost) or worst case.

i. (2 pt) How many I/Os would it take, in the worst case, to execute the following query?

SELECT sid, major FROM students WHERE gpa <= 2.0 AND is_enrolled = 1
Solution

92

Use Index A. 3 + 8 + 80 = 91 I/Os. Because of the <= in the query, we will start from the leftmost node and after reading in 3 index pages, will read in 8 leaf nodes and the 80 matching records will incur 1 I/O each. (The answer box says 92 while the explanation adds up to 91; both are copied as they appear in the official solutions.)

ii. (1 pt) Which index would we use for the above query?

  • A
  • B
  • NEITHER
Solution

A

iii. (2 pt) How many I/Os would it take, in the best case, to execute the following query?

SELECT name, gpa FROM students WHERE gpa == 4.0 AND major == 'computer science'
Solution

5

Use the alt. 3 index B on ‘major’. 3 + 20/10 = 5 I/Os.

iv. (1 pt) Which index would we use for the above query?

  • A
  • B
  • NEITHER
Solution

B

Sp21 Final Q1: Boba Trees (16 points)

(a) True or False (3 points)

i. (3 pt) Mark all statements that are true.

  • A. All paths from the root of a B+ tree to a leaf node will always pass through the same number of inner nodes.
  • B. Clustered Alternate 3 B+ trees are always at least as efficient as clustered Alternate 2 B+ trees in terms of I/O cost.
  • C. A B+ tree with height h and fanout d will always have more than (2d)(2d + 1)h−1 keys.
  • D. Having an index on a table makes inserts more efficient than inserts into a standard heap file.
  • E. Alternate 2 B+ trees are useful for frequent full scans of a relation.
  • F. Deleting a value from a B+ tree deletes it from any inner nodes it may be in as well.
  • G. None of the above
Solution

A and B.

  • A: True, B+ trees are self-balancing.
  • B: True, Alternate 3 B+ trees are the same as Alternate 2 trees if there are no duplicates, and are more efficient if there are duplicates.
  • C: False, B+ trees do not have to be completely full before splitting the root.
  • D: False, indices are more useful for reads, but are more costly for writes.
  • E: False, Alternate 2 indices have more overhead for full scans.
  • F: False, inner nodes are never deleted.

(b) (9 points)

Up-and-coming boba store Boba Trees has a lot of information about their sales this year, and they want to use indices to speed up their queries. Boba Trees has the following table orders containing information about their recent sales.

CREATE TABLE orders (
    sid INTEGER PRIMARY KEY,  // the sales id
    cid INTEGER,              // the customer id
    order TEXT,
    store_id INTEGER          // which of the store locations the order was at
);

We have 3 different indices on this table:

Index A:

  • Alternative 2, clustered B+ Tree on sid with h = 2, d = 4
  • There are 80 leaf nodes, all of which are full.
  • The first record with sid > 600 appears on the 70th leaf node (starting from the leftmost leaf node which is the 1st leaf node).

Index B:

  • Alternative 3, unclustered B+ Tree on store_id with h = 2, d = 2
  • There are 10 leaf nodes in total, and the first key with store_id > 2 is on the second leaf node.

Index C:

  • Alternative 3, unclustered B+ Tree on cid with h = 3, d = 3

Additional assumptions:

  • The orders table has 100 data pages.
  • There is exactly 1 record with cid = 50.
  • There are 80 records with cid = 100.
  • Assume that store_id has 20 unique values in the range [1,20], uniformly distributed.
  • Each data page stores 20 records.

i. (1 pt) What is the maximum number of keys that Index A can hold?

Solution

648

d = 4, so the maximum number of values is (8)(9)2.

ii. (2 pt) Calculate the minimum possible I/O cost for the following query:

SELECT * FROM orders WHERE order = 'Jasmine Milk Tea';
Solution

100

We don’t have an index on order so it’s most efficient to do a full scan, 100 pages so 100 I/Os.

iii. (2 pt) Calculate the minimum possible I/O cost for the following query:

SELECT * FROM orders WHERE cid = 50;
Solution

5

Using Index C, it takes 4 IOs to get to the relevant leaf node (3 inner nodes + 1 leaf node), and 1 IO for the relevant data page.

iv. (2 pt) Calculate the minimum possible I/O cost for the following query:

SELECT * FROM orders WHERE cid = 100 AND sid > 600;
Solution

18

Using Index A, it would take 18 IOs (2 inner nodes + 11 leaf nodes + 5 data pages). Since we have 11 leaf nodes * 8 keys per node = 88 keys to check and the index is clustered, we need to check ceil(88/20) = 5 data pages. Using Index C it would take 84 I/Os (3 inner nodes, 1 leaf node, 80 data pages).

v. (2 pt) If we wanted to do a range scan on store_id to find out how many orders we had at locations with store_id > 2, which index should we use, if any? Explain your answer.

Solution

No index. Index B is not clustered, so you would incur far more I/Os doing an index scan rather than a full scan.

(c) Bulkloading (4 points)

Uh oh! Boba Trees had an electrical fire in their store and lost Index A. They want to use bulkloading to quickly reconstruct index A; that is, a B+ tree on sid with d = 4. Assuming for this problem only that orders now contains 900 records and they use a fill factor of 0.75, answer the following questions.

i. (2 pt) How many leaf nodes would the reconstructed tree have?

Solution

150

900 / (fill factor * number of values per leaf node) = 900 / (0.75 * 8) = 150.

ii. (2 pt) What is the minimum height of the reconstructed tree?

Solution

3

A tree of height 2 and d = 4 would only be able to have at most 81 leaf nodes; therefore the tree must be of at least height 3.

Fa20 Midterm 1 Q4: B+ Trees (25 points)

1. (2 points) Which of the following are always true regarding B+ Trees? There may be zero, one, or more than one correct answer.

  • A. If d = 2, then the root node must have at least two entries.
  • B. Suppose we maintain both an Alternative 2 and an Alternative 3 B+ Tree on the primary key of some table. Inserting a value into the Alternative 2 B+ Tree will cost the same number of I/Os as inserting into the Alternative 3 B+ Tree. Assume a leaf node is stored on exactly one page.
  • C. Suppose we have two entries A and B that we want to insert into a B+ Tree. Inserting A then B into the B+ Tree results in the same final B+ Tree as inserting B then A.
  • D. Suppose we want to bulk load a B+ Tree with entries 1 to 10 with a fill factor of 3/4. The B+ Tree has an order of 2. After bulk loading with 1 to 5, the leftmost leaf node is never touched again.
Solution

B and D.

  • A: The root node can have one entry even if d = 2.
  • B: Since we are building the B+ Tree on a primary key, the Alternative 2 and Alternative 3 B+ Trees are basically the same since we cannot have any duplicates.
  • C: Inserting into a B+ Tree is not necessarily commutative when the height of the tree changes.
  • D: The leftmost leaf will be filled to the fill factor after inserting 1 to 3. Once the leftmost leaf node is filled to the fill factor, it is never touched again in the bulk loading process.

2. (2 points) Suppose we have a different type of B+ Tree where leaf nodes and inner nodes don’t necessarily have the same order. If we have d = 2 for inner nodes and d′ = 3 for leaf nodes, what is the maximum number of records we can store in an Alternative 2 B+ Tree of height 3?

Solution

750

The leaf nodes can have a maximum of 2d′ = 6 records, and the maximum fanout for inner nodes is 2d + 1 = 5. Since we have an Alternative 2 B+ Tree of height 3, the maximum number of records we can store is 6 * 53 = 750.

For questions 3 and 4, suppose we have the following B+ Tree with order d = 2.

Order 2 B+ tree with root (5, 10, 25) and leaves (3, 4), (5, 8), (10, 17), (25, 36, 50)

3. (2 points) What is the minimum number of records we can insert to increase the height of the tree?

Solution

4. Many numbers work but you could insert 51, 52, 53, 54.

4. (3 points) After inserting entries 51 to 100 (inclusive) one by one into the tree, what values are in the rightmost leaf node? Hint: Try inserting a few numbers and see if you can find a pattern.

Solution

98, 99, 100

If you insert the first few numbers you will realize that 52 causes the tree to split leaving the rightmost leaf with 50, 51, 52. Then 54 will cause the leaf to split leaving the rightmost leaf with 52, 53, 54. It seems on even inserts the tree will have the last 3 values in the rightmost node so after inserting 100, the rightmost leaf will have 98, 99, 100.

5. (3 points) Suppose we want to bulk load a B+ Tree with order d = 1. We want to bulk load 100 records using a fill factor of 1. Is the following B+ Tree a possible intermediate step during our bulk load process? Explain your answer.

Order 1 B+ tree with root (12), inner nodes (5, 9) and (20), and leaves (3, 4), (5, 8), (9, 10), (12, 16), (20, 22)

Solution

No. In the process of bulk loading those numbers, 12 would never get pushed to be the root. Instead, when 12 is bulk loaded, 9 is pushed up.

For questions 6–10, suppose we have the following table shown below. Also, assume that our buffer is large enough to hold all pages needed and is empty at the start of each question.

CREATE TABLE Restaurants (
    rid INTEGER PRIMARY KEY,
    name VARCHAR,
    type VARCHAR,
    size INTEGER,
    num_ratings INTEGER,
    rating FLOAT
);

6. (2 points) Suppose we have a height 3 Alternative 1 B+ Tree with order d = 2 on rid. What is the minimum number of I/Os it would take to execute the following query (Assume there is at least one matching tuple):

UPDATE Restaurants SET num_ratings = 500 WHERE rid = 100;
Solution

5. It takes 3 I/Os to reach the leaf, 1 I/O to read in the leaf, and 1 I/O to write the leaf back to disk.

7. (2 points) Now suppose we have an unclustered Alternative 2 B+ Tree instead of an Alternative 1 B+ Tree. What is the minimum number of I/Os it would take to execute the same query (Assume there is at least one matching tuple)?

Solution

6. It takes 3 I/Os to reach the leaf, 1 I/O to read in the leaf, 1 I/O to read in the data page, and 1 I/O to write the data page back to disk. Note that we do not need to write the leaf page back to disk since we are only updating num_ratings.

We decide to mix things up by creating an Alternative 2 unclustered B+ Tree with height 3 and order d = 2 on (size, num_ratings). As a reminder, for multi-column keys, comparisons are done on the first element in the key, and the second elements are compared to break ties. For problems 8–10, assume the following:

  • There are no duplicate (size, num_ratings) pairs.
  • There are exactly 5 records per page in the heap file corresponding to the B+ Tree.
  • There are 100 leaf nodes with exactly 3 entries in each leaf node. Each leaf node fits exactly on one page.
  • The table has 60 data pages in total.
  • The first entry with size=20 appears on the first entry of the 91st leaf node.
  • The last entry with num_ratings=500 appears on the last entry of the 86th leaf node.
  • None of the index pages are in the buffer pool at the start of each part.

Now, suppose we want to execute the following query:

SELECT * FROM Restaurants WHERE size >= 20 AND num_ratings <= 500;

8. (3 points) In the worst case what is the number of I/Os it would take to execute the query?

Solution

43

The useful piece of information is that the 91st leaf contains the first entry with size=20 since our tree is first ordered on size and then ratings. It takes 3 I/Os to reach that leaf. In the worst case we must scan all leaves 91-100 (10 I/Os), and we find that all records in those leaves satisfy our WHERE clause. Since this is an Alternative 2 unclustered index, we need 1 I/O for every matching tuple or 30 I/Os. Thus, our total I/O cost is 3 + 10 + 30 = 43.

9. (3 points) If we had a clustered index instead of an unclustered index, how many I/Os would it take to execute the query in the worst case scenario?

Solution

19

We follow a similar procedure as the previous problem in terms of reaching our leaf and scanning our leaves but this time we only need 1 I/O per page of matching tuples. Since our data pages hold 5 tuples we have 30/5 or 6 I/Os to access our clustered data.

(We also accepted 20 if you considered the extreme worst case that the 30 tuples would be spread out across 7 heap pages instead of 6, similar to a vitamin question we asked.)

Now, assume we want to execute the following query:

SELECT * FROM Restaurants WHERE size >= 20 OR num_ratings <= 500;

10. (3 points) What is the minimum number of I/Os it would take to execute the query? Assume that the index is unclustered for this part.

Solution

60. Our index is useless as we have no guarantee that the tuples we are searching for are ordered in our leaves. Therefore, we need to scan the entire table.