# Indexes & B-Trees

> See how a B-tree index finds a row in a few steps instead of reading the whole table, which queries it speeds up, and what it costs on every write.

Subject: SQL | Lesson 39 of 44 | 7 min read
Interactive lesson: https://codewithanimation.in/sql/indexes-and-b-trees
Previous: [Views](https://codewithanimation.in/sql/views.md) | Next: [Composite & Partial Indexes](https://codewithanimation.in/sql/composite-and-partial-indexes.md)

## An index is a sorted shortcut

Without an index, to find the rows where `city = 'Oslo'` the database has to scan the table row by row. That is a **sequential scan**. An **index** is a separate, sorted structure that points at table rows, like the index at the back of a book: you look up the word and go straight to the page.

The default kind in PostgreSQL is a **B-tree**. It keeps the keys in sorted order in a tree of pages. The top page (the root) tells you which page to read next, and so on down to a **leaf** page that points at the table rows.

## A few steps, however big the table

Each level of the tree narrows the search a lot, so even a huge table needs only a handful of page reads to find one row. A table of 26 million rows does not take a million times longer to search than a table of 26.

## Create one and see what it can do

```sql
CREATE INDEX places_city ON places (city);
```

In the lab the tree has 3 levels. Looking up `city = 'Oslo'` visits the root, one inner page and one leaf: 3 pages, then it reads one table row. A sequential scan would read all 26 rows.

A B-tree works for `=`, for ranges (`<`, `<=`, `>=`, `>`, `BETWEEN`), for `IN` and for `IS NULL`. It can also hand back rows in sorted order, which can save a sort. A range is cheap because the keys are sorted: find the start, then read along the leaves.

`LIKE 'Ro%'` can use the index, because it is a range from `Ro` to `Rp`. `LIKE '%a'` cannot, because the keys are sorted by their first letter, not their last. (If the database does not use the C locale, you need a special operator class for pattern matching.)

## Common mistake: Indexes are not free

The database must keep every index in step with the table. Each `INSERT`, `UPDATE` and `DELETE` also changes the index, which adds work. When a leaf page is full, the page splits in two and a new entry goes up into the parent, which can cascade, and when the root splits the tree gets a level taller. Most inserts just fit, but not all.

More indexes mean slower writes and more disk space. The manual says indexes that are seldom or never used should be removed. Building a big index also blocks writes to the table by default, unless you build it concurrently.

The planner decides whether to use an index. If a query wants most of the table, reading it in order is cheaper than jumping through an index for every row, so the planner may ignore the index, and on a tiny table it usually does. It chooses using statistics, so run `ANALYZE` after big changes.

Do not expect an index you did not create. A primary key or a UNIQUE constraint creates a unique B-tree index for you, but a foreign key does not index the referencing column. If you join or look up by that column, add an index yourself.

## Tip: Index what you filter, join and sort by

Look at the columns in your `WHERE`, `JOIN ... ON` and `ORDER BY` for the queries that matter and are slow. Add an index there, check with `EXPLAIN` that it is used, and drop it again if it is not.

## Try it: Lookup with and without an index

Run the four queries with the index on, then with it off. Then try the two inserts and watch the tree.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/indexes-and-b-trees

## Check yourself

### Question 1

The tree has 3 levels. How many tree pages does an index lookup of one key visit?

- A. 3: one per level, from the root down to a leaf
- B. All of them
- C. 1, because the root has the answer

Correct answer: A

The search goes down one page per level, so the work grows with the depth of the tree, which grows very slowly.

- Why not B: That would be no better than reading everything. A lookup follows one path from the root to one leaf.
- Why not C: The root only tells you which page to read next. The row pointers are in the leaves.

### Question 2

A B-tree index exists on `city`. Which query can it NOT help with?

- A. WHERE city LIKE '%a'
- B. WHERE city LIKE 'Ro%'
- C. WHERE city >= 'L' AND city < 'P'

Correct answer: A

The keys are sorted by their first letter. A pattern that starts with % has no starting point to look up.

- Why not B: A pattern anchored at the start is a range of keys, so the index can find it.
- Why not C: Ranges are exactly what a sorted tree is good at.

### Question 3

What is the main cost of adding another index to a busy table?

- A. Every INSERT, UPDATE and DELETE must also update the index, and it uses disk space
- B. SELECT queries get slower
- C. The table can no longer be sorted

Correct answer: A

The manual says the system has to keep the index synchronized with the table, which adds overhead to data manipulation operations.

- Why not B: An index is meant to speed up reads. The cost falls mostly on writes and storage.
- Why not C: An index does not change the table. It is a separate structure.

## Remember this

- An index is a sorted structure that points at table rows. PostgreSQL's default is the B-tree.
- A B-tree finds one key in a few steps (one page per level) and handles =, ranges, IN, IS NULL, and LIKE 'abc%'.
- LIKE '%abc' cannot use a B-tree, because the keys are sorted from the start.
- Indexes slow down writes and take space, so index what you really filter, join and sort by, and check with EXPLAIN.
