Sub topic 1
The problem: scanning every row
Prerequisites
This chapter assumes you know basic SQL: SELECT, WHERE, ORDER BY, and JOIN. You should understand tables, rows, columns, and primary keys. A basic sense of linear versus logarithmic growth helps.
The problem: scanning every row
A full table scan reads every row in a table and checks each one against the WHERE clause. On a table with 1,000 rows, this is fast. On a table with 100 million rows, the same query reads 100 million rows.
The cost grows with the table. Doubling the rows roughly doubles the work. Computer scientists call this linear growth, written O(n).
What an index is and what it trades
An index is a separate structure that stores a column's values in sorted order, each paired with a pointer to its row. The database searches the index first, then fetches only the matching rows.
An index trades storage and write speed for read speed. It takes disk space, and every INSERT, UPDATE, or DELETE on an indexed column must also update the index.
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
total_cents integer NOT NULL
);
CREATE INDEX orders_customer_id_idx ON orders (customer_id);Inside a B-tree index
Most indexes use a B-tree, a balanced tree of sorted pages. The top page is the root. Internal pages point to lower pages, and leaf pages hold the keys and row pointers. Each page holds hundreds of keys, so the tree stays shallow. A table with a billion rows often needs only three or four levels.
A lookup visits one page per level, so it takes about log(n) page reads. Computer scientists write this O(log n).
Point lookups, range scans, and ordering
A point lookup finds one key. The engine walks from the root to a leaf and reads the matching row pointer.
A range scan, such as created_at >= '2026-01-01', finds the first matching leaf entry. It then reads the neighboring leaf entries in order, because the leaves are sorted. Sorted storage also lets the database return rows already in order for ORDER BY without a separate sort step.
Exercise
A table has 10 million rows and a query filters on an unindexed column. Roughly how many rows does the database read, and how would an index on that column change the work?
Show answer
It reads about 10 million rows in a full scan. With a B-tree index on that column, it walks a few levels to the first match and reads only the matching index entries and their rows.