Learning navigation

Code with Animation

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.

SQL7 min readConcept 39 of 44

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

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.)

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.

SELECT * FROM places
WHERE city = 'Oslo';
 
-- index on city
CREATE INDEX places_city ON places (city);

Table places, 26 rows in the order they were added

OsloLimaRomeCairoBernAccraSeoulParisQuitoDohaRigaTokyoLyonMinskHanoiNuukPerthSofiaKyivDelhiDakarTurinRabatLagosViennaZagreb

B-tree on city: 3 levels

Root

Oslo

Inner level

DakarDohaLagosLyon
QuitoRomeTokyo

Leaves (point to table rows)

AccraBernCairo
DakarDelhi
DohaHanoiKyiv
LagosLima
LyonMinskNuuk
OsloParisPerth
QuitoRabatRiga
RomeSeoulSofia
TokyoTurinViennaZagreb

Index: 3 tree nodes visited, 1 table row read.

The index goes root, then one inner node, then one leaf: 3 nodes, however big the table. It finds Oslo and goes to that one table row. A sequential scan would read 26 rows.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1The tree has 3 levels. How many tree pages does an index lookup of one key visit?
  2. 2A B-tree index exists on `city`. Which query can it NOT help with?
  3. 3What is the main cost of adding another index to a busy table?

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.

Done with this concept?

Mark it complete to track your progress. No login needed.