Menu

1 / 2

Understanding Database Indexes by Building a Tiny B-Tree

DEV Community: python·Emma Clements·14 days ago
#JVVOZxnt
#devtopython#devto#dev#node#keys
Long article (3042 words) — no AI summary yet.
Reading 0:00
15s threshold

An index is not magic. It is a sorted data structure that the database keeps up to date for you. In this post we build one from scratch in about 80 lines of Python, test it, and then watch a real database (SQLite) behave exactly the way our toy does.

Everything here uses only the Python standard library and was run on Python 3.13.

The problem: scanning

Take a users table with 500,000 rows and ask for one user by email. With no index, the database has no choice but to read every row until it finds a match. SQLite's query plan calls this a SCAN .

I measured it (SQLite 3.53.1, in-memory, 500k rows, average of 20 lookups):

Query plan Time per lookup

No index SCAN users ~22.6 ms

Index on email SEARCH users USING INDEX idx_email (email=?) ~0.002 ms

That is roughly a 10,000x difference, and the gap grows with the table. Timings depend on your machine, so treat the ratio, not the absolute numbers, as the point.

Why a tree?

We need a sorted structure so we can jump to a key instead of walking to it.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.