Lesson 1 · Unit 02
The B-tree
From reading every row to a few steps down a tree
What you practise
- A full table scan is O(n)
- An index is a sorted tree, so lookups and ranges are O(log n)
- The primary key index
- What an index costs on every write
Try a question from this lesson
Pick one
A table holds 1,000,000 users in no particular order. To find the one with a given email, how many rows must the database read in the worst case?
Correct answer
1,000,000
Why
With no order there is nothing to exploit: the email could be in the very last row checked. This is a full table scan, the same O(n) linear search you would do on an unsorted list.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
An index is a sorted copy
An index stores one column's values in sorted order, each with a pointer to its row. It is kept as a B-tree, so finding a value takes a few steps down from the root.
Query plans tell you whether one was used. SCAN means every row was read. SEARCH means an index was used to jump to the right rows.
CREATE TABLE users(id, email, name);
CREATE INDEX idx_email
ON users(email);10 more exercises in the app
- 2× type the answer
- 4× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.