Indexes for Beginners: The Back-of-the-Book Analogy
Sooner or later someone will say "add an index" about a slow query. If that word is still mysterious, this post is for you. We will use the index at the back of a book, which works in almost exactly the same way.
Finding a word in a book
Imagine a 500-page cookbook and you want every recipe with ginger.
- Without an index: you turn every page and look. That is what a database does when it reads a whole table, called a full table scan.
- With an index: you flip to the back, find "ginger" in alphabetical order, and read the page numbers. Then you go straight to those pages.
A database index is the same idea: a separate, sorted list of values from one or more columns, each pointing to where the matching rows live.
Creating one
CREATE INDEX idx_recipes_title ON recipes (title);
Now a query like this can use the index instead of reading every row:
SELECT * FROM recipes WHERE title = 'Ginger biscuits';
You do not have to mention the index in your query. The database decides by itself whether using it is worthwhile.
You already have some
When you create a primary key, the database creates an index for it automatically, because finding a row by its key is so common. Many databases do the same for UNIQUE constraints. That is part of why looking up a row by id is fast.
When an index helps
| Query | Helped by an index on title? |
|---|---|
WHERE title = 'Pancakes' | Yes |
WHERE title LIKE 'Pan%' | Often, since the start of the word is known |
WHERE title LIKE '%cake' | Not an ordinary index; the start is unknown |
ORDER BY title | Can help, since the index is already sorted |
WHERE calories < 300 | No, a different column |
What indexes cost
A book index takes pages, and someone has to update it when recipes are added. Database indexes are similar:
- they take extra storage
- every INSERT, UPDATE and DELETE must also update the index
- too many indexes slow down changes
So we do not index every column. We index columns that our common queries search or sort by.
Should a beginner worry about this?
On small practice tables, with a few hundred rows, you will rarely notice a difference: reading the whole table is already instant. Indexes matter when tables grow to many thousands of rows and the same query runs often. It is good to understand the idea now, so that when a page in your app becomes slow, "is there an index on the column I search by?" is one of your first questions.
Seeing it for yourself
In SQLite, put EXPLAIN QUERY PLAN before a query. Without an index you will see a line containing SCAN; with a suitable index, a line containing SEARCH ... USING INDEX. Our post on your first slow query goes one step further. For deeper index design, our sister site databaseintegrate.com has detailed guides.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.