Database Indexes and Performance · Lesson 50 of 112

Database Index Internals

What you will learn

  • Why sorted data can be searched by halving
  • How many steps a search needs for 1,000 and 1,000,000 values
  • That real databases use a B-tree
  • What an index stores and where to see it

1. Searching sorted data

Look for the number 999,999 in an unsorted list of one million numbers: you must check them one by one. In a sorted list there is a much faster way, binary search: look at the middle, decide which half the target is in, throw the other half away, and repeat. Count the steps in both methods:

def linear(items, target):
    steps = 0
    for x in items:
        steps += 1
        if x == target: return steps
    return steps

def binary(items, target):
    lo, hi, steps = 0, len(items) - 1, 0
    while lo <= hi:
        steps += 1
        mid = (lo + hi) // 2
        if items[mid] == target: return steps
        if items[mid] < target: lo = mid + 1
        else: hi = mid - 1
    return steps

for n in (1000, 1000000):
    items = list(range(n))
    print(n, "linear worst:", linear(items, n - 1), "binary worst:", binary(items, n - 1))
1000 linear worst: 1000 binary worst: 10
1000000 linear worst: 1000000 binary worst: 20

A thousand times more data (1,000 to 1,000,000) made the scan a thousand times longer, but the halving search only twice as long (10 steps to 20). That is why an index stays fast as tables grow.

2. The B-tree

A database does not keep an index as one long list, because rows are added and removed all the time and the index lives on disk. The usual structure is a B-tree (balanced tree): a tree of small sorted blocks, where each block points to the blocks below it. A search starts at the top block, picks the right branch, and reaches the right place after a few steps, in the same spirit as halving. The tree keeps itself balanced as data changes, so searches stay fast. SQLite, and most other relational databases, use B-trees for ordinary indexes; you do not need to manage them yourself.

3. B-tree or hash?

A B-tree keeps values in order. That is why it can answer more than "is this value here?": it can also find a range (amount BETWEEN 100 AND 200) and return rows already sorted (ORDER BY). Some databases also offer a hash index, which turns the value into a number and jumps to a slot. A hash is excellent at "equals" and useless for "between", because hashing destroys the order. The PostgreSQL documentation says exactly this: a hash index "can only handle simple equality comparisons", while B-trees "can handle equality and range queries" and can also return data in sorted order. We can imitate the two in Python, a dict (a hash) and a sorted list:

import bisect
ids = list(range(0, 1000000, 2))      # sorted even numbers
d = {x: True for x in ids}
print("equality via dict (hash):", 500000 in d)
lo = bisect.bisect_left(ids, 1000); hi = bisect.bisect_left(ids, 1010)
print("range 1000..1009 via sorted list:", ids[lo:hi])
print("first 3 in order via sorted list:", ids[:3])
equality via dict (hash): True
range 1000..1009 via sorted list: [1000, 1002, 1004, 1006, 1008]
first 3 in order via sorted list: [0, 2, 4]

The dict cannot give "everything between 1000 and 1010" or "the first three in order" without looking at every key; the sorted list can, by jumping to the start and reading along. That is why the default index in nearly every database is a B-tree, and why this course uses "index" to mean a B-tree unless it says otherwise.

4. What an index stores

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The index you create lives in your browser's copy; Reset data removes it.

An index on a column stores each value together with a pointer to its row (in SQLite, the row's rowid), kept in sorted order. It is a small second copy of part of your data. We can see it in SQLite's catalogue, and see the sorted order directly:

CREATE INDEX idx_customers_city ON customers (city);
SELECT type, name, tbl_name FROM sqlite_master WHERE name = 'idx_customers_city' OR name = 'customers';
SELECT city, customer_id FROM customers ORDER BY city, customer_id LIMIT 4;
type   name                tbl_name
-----  ------------------  ---------
table  customers           customers
index  idx_customers_city  customers
(2 rows)

city   customer_id
-----  -----------
Accra           56
Accra           57
Accra           97
Accra           99
(4 rows)
CREATE INDEX idx_customers_city ON customers (city);
SELECT type, name, tbl_name FROM sqlite_master WHERE name = 'idx_customers_city' OR name = 'customers';
SELECT city, customer_id FROM customers ORDER BY city, customer_id LIMIT 4;
type   name                tbl_name
-----  ------------------  ---------
table  customers           customers
index  idx_customers_city  customers
(2 rows)

city   customer_id
-----  -----------
Accra           15
Accra           19
Accra           33
Accra           50
(4 rows)
CREATE INDEX idx_students_last_name ON students (last_name);
SELECT type, name, tbl_name FROM sqlite_master WHERE name = 'idx_students_last_name' OR name = 'students';
SELECT last_name, student_id FROM students ORDER BY last_name, student_id LIMIT 4;
type   name                    tbl_name
-----  ----------------------  --------
table  students                students
index  idx_students_last_name  students
(2 rows)

last_name  student_id
---------  ----------
Abdi                8
Abdi               13
Abdi              108
Abdi              181
(4 rows)

The catalogue lists the table and the index as separate objects. The last result shows what the index holds: the values in sorted order, each with the id of its row. Because equal values sit side by side, finding every row with one value means finding the first and reading along.

Worked example: how many steps for 10 million rows?

Each halving step cuts the search range in two, so the number of steps is about how many times you can halve the count before reaching 1. For 1,000 that is 10 (2 to the power 10 is 1,024). For 1,000,000 it is 20 (2 to the power 20 is 1,048,576). For 10,000,000 it is about 24, because 2 to the power 24 is 16,777,216 and 2 to the power 23 is only 8,388,608. A B-tree has more branches per block, so it needs even fewer levels, but the lesson is the same: the cost grows very slowly.

Common mistakes

  • Thinking the index is the table. It is a separate structure that points to table rows.
  • Expecting an index to help questions it is not sorted for, such as LIKE '%x' (lesson 7.4): the index is sorted by the start of the value.
  • Believing the step counts are exact for every database. The binary search count is a model; real B-trees differ in the details but behave the same way as tables grow.

Key takeaways

  • Sorted data can be searched by halving: about 20 steps for a million values.
  • A scan's cost grows with the table; an index search grows very slowly.
  • Databases keep indexes as B-trees that stay balanced as data changes.
  • An index stores sorted values plus pointers to rows, as a separate object.
  • A B-tree handles equality, ranges and sorting; a hash index handles only equality.

Practice

1. How many steps does binary search need, at most, for 1,000 sorted values?

Show answer

About 10 (the lesson's run showed 10).

2. Why is a plain sorted list a poor index for a table with constant inserts?

Show answer

Every insert would have to shift items to keep it sorted. A B-tree is designed to take inserts and deletes cheaply while staying sorted and balanced.

3. What two things does an index entry hold?

Show answer

The column value and a pointer to the row that has it.

4. In the lesson's last output, why do the Barishal ids come out together?

Show answer

The index is sorted by city, so equal cities are neighbours.

5. Where in SQLite can you see the list of indexes?

Show answer

In the sqlite_master catalogue table (type index), and with PRAGMA index_list(table) (lesson 7.3).

6. A teammate proposes a hash index on price for the query WHERE price BETWEEN 100 AND 200. Will it help? Why?

Show answer

No. A hash index only answers equality (price = 150), because hashing throws away the order of the values. A B-tree keeps values sorted, so it can jump to 100 and read on to 200.