← All posts

What a Database Index Is and Why Your Query Is Slow

Your project works fine with 20 rows in the database and crawls with 20,000. Here is the one concept that fixes most of that.

🚀 The Simple Version

A database index is exactly like the index at the back of a textbook. Without it, finding "photosynthesis" means reading every single page. With it, you jump straight to page 214. An index does that for your database queries.

Why Queries Get Slow Without One

By default, searching for a row (say, a user by email) means the database checks every single row one by one — this is called a "full table scan." Fine for 20 rows, painfully slow for 200,000.

How You Actually Add One

In most databases, it's a single line:

-- SQL
CREATE INDEX idx_users_email ON users(email);

// MongoDB / Mongoose
userSchema.index({ email: 1 });

Now looking up a user by email is nearly instant, even with millions of rows, because the database keeps a pre-sorted lookup structure instead of scanning everything.

The Trade-off Nobody Mentions

Indexes aren't free. Every index speeds up reads but slightly slows down writes (because the index has to update too) and takes extra storage. The rule of thumb: index the columns you filter/search/sort by often — not every column "just in case."

Where to Actually Use This

Any field you put in a WHERE, a MongoDB find({...}) filter, or a login lookup (like email or username) is a strong candidate. This single habit is one of the most common things separating "student project" performance from "production-ready" performance.