Database indexes explained: why some queries are fast and others crawl
An index is a separate data structure the database maintains so it can find rows without scanning the whole table. Think of the index at the back of a book: instead of reading every page, you jump straight to the right one.
How it works. Most relational databases use a B-tree index by default. It keeps values sorted in a balanced tree, so finding a value, or a range of values, takes a handful of steps even across millions of rows.
Why queries still crawl:
- No index on the filtered column. The database falls back to a full table scan.
- Functions on the column.
WHERE lower(email) = ...can't use a plain index onemailunless you create an expression index. - Wrong column order in a composite index. An index on
(country, city)helps queries filtering by country, but not by city alone. - Low selectivity. Indexing a boolean column rarely helps because half the table matches anyway.
The trade-off. Every index speeds up reads but slows down writes and uses storage, because the database must update it on every insert or update. Adding indexes "just in case" can hurt.
The best habit is to read the query plan (EXPLAIN in most databases) before guessing.
What's the most dramatic speedup you've gotten from a single index? And how do you decide when a table has too many?
Comments · 4
The back-of-the-book analogy finally made indexes click. Can't believe it took me this long.
Worth remembering that every index slows writes slightly. Add the ones your queries actually need.
How can I tell which columns deserve an index? Is EXPLAIN the way to start?
EXPLAIN is the right start. Look for full table scans on big tables, then index the columns used in WHERE and JOIN.