DEV Community

Cover image for Database Indexes: The Back Page of the Book
Mohsen Fallahnejad
Mohsen Fallahnejad

Posted on Originally published at bitlyst.blog

Database Indexes: The Back Page of the Book

Picture this: your app works great with 100 users. A year later you have 2 million, and the login page suddenly takes three seconds. You didn't change any code. So what happened?

Very often, the answer is a missing database index. Let's see what that is, in plain words.

The whole idea in one picture

Think about a big cookbook. You want the recipe for pancakes. You have two choices:

  1. Start at page 1 and flip through every page until you find it.
  2. Go to the index at the back, find "Pancakes → page 212", and jump straight there.

A database index is the index at the back of the book. It tells the database exactly where to look, so it doesn't have to read every row.

That's it. Everything else in this post is just details on top of that picture.

How it works

When you run a query like this:

SELECT * FROM users WHERE email = 'sara@example.com';
Enter fullscreen mode Exit fullscreen mode

the database needs to find the matching row. Without an index, it does option 1 from the cookbook: it reads every single row and checks the email. This is called a full table scan. With 100 rows, nobody notices. With 2 million rows, you notice.

Now you add an index:

CREATE INDEX idx_users_email ON users (email);
Enter fullscreen mode Exit fullscreen mode

The database builds a separate, small list: every email, kept in sorted order, each one with a pointer to its row. Like the cookbook index, sorted from A to Z.

Because the list is sorted, the database can find a value the way you find a word in a dictionary: open the middle, see if you went too far, cut the rest in half, repeat. For a million rows that's only about 20 steps, because you can halve a million only about 20 times before one row is left. Compare that with checking a million rows one by one.

AI-generated illustration. Same question, same data. The only difference is whether someone kept a sorted list.

(If someone asks what the list really looks like inside: it's usually a B-tree, a sorted tree that stays balanced as you add rows. You don't need more than that name for most conversations.)

The catch: indexes aren't free

If indexes make reads faster, why not add one to every column? Go back to the cookbook.

  • It takes pages. The index at the back of the book uses paper. A database index uses disk space and memory too.
  • It needs upkeep. Every time the author adds a recipe, someone has to update the index. Every time you INSERT, UPDATE or DELETE a row, the database has to update every index on that table as well. So writes get a bit slower.

So the rule is simple: index the columns you search, filter, join or sort by often. Don't index things you never look up.

In practice

Good candidates for an index:

  • Columns in WHERE: email, user_id, status
  • Columns you JOIN on: foreign keys like orders.user_id
  • Columns you ORDER BY on big tables: created_at

Most databases create an index for your primary key automatically, and for UNIQUE columns too, so WHERE id = 42 is already fast.

Not sure if a query uses an index? Ask the database. Put EXPLAIN in front of it:

EXPLAIN SELECT * FROM users WHERE email = 'sara@example.com';
-- "Seq Scan on users"    ← reading every row (no index used)
-- "Index Scan using idx_users_email" ← jumping straight there
Enter fullscreen mode Exit fullscreen mode

How often will this bite you? Honestly, almost every growing app hits it at least once. The good news: it's usually a one-line fix, and the slow query shows you exactly where it is.

Say it in an interview

"An index is like the index at the back of a book. The database keeps a sorted copy of one or more columns, usually as a B-tree, with pointers to the rows. So instead of scanning the whole table, it can find a value in a few steps. The trade-off is extra storage and slower writes, because every insert or update also has to update the index. So I index the columns I filter, join and sort by, and check with EXPLAIN."

Cheat sheet

Question Short answer
What is an index? A sorted list of column values with pointers to rows
Why is it fast? Sorted data can be searched by halving, not row by row
No index means? Full table scan: read every row
What does it cost? Disk space, and slower INSERT / UPDATE / DELETE
What to index? Columns in WHERE, JOIN and ORDER BY
How to check? EXPLAIN your query

Going deeper

Advanced and optional. Everything above is enough to explain this in an interview. This part is for the curious: full numbers, edge cases and what's still unproven.

Composite indexes and the "phone book" rule

An index can cover more than one column:

CREATE INDEX idx_users_last_first ON users (last_name, first_name);
Enter fullscreen mode Exit fullscreen mode

Think of a phone book sorted by last name, then first name. It helps when you search by last_name, or by last_name and first_name. It does not help when you search only by first_name, because the first names are scattered all over the book. Column order matters: put the column you always filter by first.

When the database ignores your index

  • The query wraps the column in a function. WHERE LOWER(email) = '...' can't use a plain index on email. Many databases let you index the expression itself (CREATE INDEX ... ON users (LOWER(email))).
  • The filter matches most of the table. If status = 'active' is true for 95% of rows, reading the whole table is cheaper than jumping back and forth. The query planner decides this for you.
  • Leading wildcards. LIKE '%gmail.com' can't use the sorted order, for the same reason you can't look up words by their last letters in a dictionary.

Further reading


Originally published on Bitlyst.

Top comments (0)