SQL from Zero › Module 1: How a database thinks

How the database finds things fast

Full table scans, indexes, and why indexes aren't free.

Lesson 4 of 33 · about 10 minutes

Video: The index at the back of the bookThe narrated video for this lesson is coming soon. The lesson below covers the same ideas.

The lesson

Pick up a big textbook and try to find every page that mentions "photosynthesis". You could read all 500 pages from start to finish. That works, but it's slow. Or you could turn to the index at the back, find "photosynthesis: pages 42, 87, 233", and jump straight there.

Databases face the same choice. Reading every row in a table is called a full table scan. It's fine for 20 books, but painful for 20 million.

So a database can keep an index on a column. An index is a sorted list of that column's values, and each value points to where its rows live. If there's an index on genre, a search for Fantasy books jumps straight to the right rows.

Remember the planner from the last lesson? This is exactly the kind of choice it makes: "There's an index on genre, so I'll use it instead of reading every row."

Indexes aren't free, though. Just as a textbook's index has to be updated whenever pages change, the database has to update an index every time you add or change a row. So you add indexes to the columns people search on a lot, not to every column.

Key ideas
  • Without an index, the database reads every row: a full table scan.
  • An index is like a book's index: a sorted shortcut to the right rows.
  • Indexes make searching faster but make adding and changing data a little slower, so use them where they help most.

Practise

Loading practice…

Quick check

1. What is a full table scan?

2. Why not put an index on every column?

3. A book's index is like a database index because…