1. Home
  2. Blog
  3. Insights

The Index That Saved MySQL From Scanning 2.5 Million Rows to Just 10

We Didn’t Upgrade the Server. We Fixed the Query.

At CodeROG, we work on systems of very different ages.

Some are modern applications built from the ground up with current frameworks, carefully designed databases, and observability from day one.

Others are older production systems that have been running successfully for years.

And sometimes, those older systems have something very interesting hidden inside them:

millions of rows, years of accumulated data, and queries that were originally written when the database was much smaller.

This is the story of one such system.

While working on an older e-commerce platform for one of our major clients, we encountered a database performance problem that initially looked like a server problem.

The application had a large orders table.

The table contained around 2.5 million rows.

One of the application’s queries was taking a significant amount of time.

The application was slow.

The database was doing a lot of work.

And the natural question was:

“Do we need a bigger server?”

More RAM.

More CPU cores.

Faster storage.

Maybe even a larger database server.

But after investigating the query, we found something much more interesting.

The server wasn’t necessarily the problem.

MySQL was simply doing far more work than it needed to.

After adding the right index, the query went from effectively scanning around 2.5 million rows to examining roughly 10 rows.

We didn’t upgrade the server.

We didn’t add more RAM.

We didn’t increase CPU.

We fixed the query.


The Problem: A Simple Query That Wasn’t Simple for MySQL

The system was an older e-commerce application that stored customer orders.

For simplicity, let’s imagine the relevant table looked something like this:

CREATE TABLE orders (
    id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    customer_id BIGINT UNSIGNED NOT NULL,
    status VARCHAR(20) NOT NULL,
    created_at DATETIME NOT NULL,
    total DECIMAL(10,2) NOT NULL
);

Over the years, the application had accumulated a significant amount of order data.

The table had grown to approximately:

RowsApproximate Situation
10,000Small
100,000Still comfortable
500,000Noticeable
1,000,000Performance starts mattering
2,500,000Queries need to be designed carefully
10,000,000+Indexing becomes critical

At 10,000 rows, you can get away with a lot.

At 2.5 million rows, MySQL has to make very different decisions.

The application needed to find recent completed orders for a particular customer.

The query was conceptually similar to:

SELECT *
FROM orders
WHERE customer_id = 18472
  AND status = 'completed'
ORDER BY created_at DESC
LIMIT 10;

Logically, this sounds incredibly cheap.

We’re asking for:

“Give me the latest 10 completed orders belonging to customer 18472.”

But MySQL doesn’t automatically know where those records are.

It needs an efficient way to find them.

And that’s where indexes become important.


What Happens Without the Right Index?

Suppose the only index we have is the primary key:

PRIMARY KEY (id)

The database knows how to quickly find:

WHERE id = 12345

But our query isn’t searching by id.

It’s searching by:

customer_id
status
created_at

So MySQL may have to inspect a huge portion of the table to figure out which rows match.

Conceptually, the database could end up doing something like:

Row 1       → customer 1001 → no
Row 2       → customer 4921 → no
Row 3       → customer 18472 → maybe
Row 4       → customer 7311 → no
...
Row 2,500,000 → check again

The application only needs 10 rows.

But the database may have to examine millions of rows to find them.

That difference is everything.


2.5 Million Rows vs 10 Rows

This is the part that is easy to underestimate.

The application developer sees:

LIMIT 10

and thinks:

“MySQL only returns 10 records.”

But LIMIT 10 does not necessarily mean MySQL only examines 10 rows.

It means:

“Stop returning results after you have found 10 matching rows.”

Those are very different things.

For example:

SELECT *
FROM orders
WHERE customer_id = 18472
LIMIT 10;

Without a useful index, MySQL may need to inspect thousands or millions of rows before finding 10 matches.

The database doesn’t magically know where the matching rows are.


The First Thing We Did: EXPLAIN

Before changing anything, we wanted to understand what MySQL was actually doing.

So we ran:

EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 18472
  AND status = 'completed'
ORDER BY created_at DESC
LIMIT 10;

A simplified result might look like this:

ColumnValue
typeALL
possible_keysNULL
keyNULL
rows2,500,000
ExtraUsing where; Using filesort

The most interesting part was:

type: ALL

ALL is MySQL’s indication that it is performing a full table scan.

In other words:

“I don’t have a useful index for this query, so I’ll inspect the table.”

And then:

rows: 2,500,000

That’s the number that got our attention.

The application needed 10 records.

MySQL potentially had to examine around 2.5 million.


Why Full Table Scans Become Expensive

A full table scan isn’t automatically bad.

This is important.

If a table has 100 rows, scanning all 100 rows is completely reasonable.

Even scanning a few thousand rows may be perfectly fine.

The problem appears when the amount of work grows with the size of the table.

Imagine:

10,000 rows
     ↓
scan 10,000

100,000 rows
     ↓
scan 100,000

1,000,000 rows
     ↓
scan 1,000,000

2,500,000 rows
     ↓
scan 2,500,000

The query gets slower as the table grows.

That’s dangerous for production systems because the database usually doesn’t stop growing.

Today’s 2.5 million rows could become:

5 million
10 million
25 million
50 million

If the query architecture doesn’t scale with the data, performance eventually collapses.


Adding an Index

The query filters by:

customer_id
status

and sorts by:

created_at DESC

So the first thing we considered was a composite index:

CREATE INDEX idx_orders_customer_status_created
ON orders (customer_id, status, created_at);

This creates an index containing the columns needed by the query.

Conceptually, instead of MySQL looking through the entire table:

2,500,000 rows
       ↓
    WHERE
       ↓
10 matches

it can navigate the index:

customer_id
      ↓
status
      ↓
created_at
      ↓
matching rows

The database can now locate the relevant part of the data much more efficiently.


What Changed?

We ran EXPLAIN again.

The result now looked more like:

ColumnBeforeAfter
typeALLref
possible_keysNULLidx_orders_customer_status_created
keyNULLidx_orders_customer_status_created
rows~2,500,000~10
ExtraUsing where; Using filesort—

The most important number:

2,500,000 → ~10

That’s an enormous reduction in work.

The query wasn’t returning fewer rows.

The application logic hadn’t changed.

The database still contained the same 2.5 million rows.

We simply gave MySQL a better path to find the rows.


But What Exactly Is an Index?

A MySQL index is a data structure that helps the database locate rows without scanning the entire table.

Think about a book.

Suppose you want to find every page mentioning:

"database indexing"

Without an index, you’d start at page 1 and read every page.

That’s essentially a table scan.

But a book usually has an index at the back.

You look up:

Database indexing ........ 42, 87, 153, 291

Now you know where to go.

You don’t need to read every page.

A database index works on the same basic principle.


The Important Part: Index Order

This is where database indexing gets interesting.

Suppose we create:

CREATE INDEX idx_orders
ON orders (customer_id, status, created_at);

The order matters.

It’s not equivalent to:

(status, customer_id, created_at)

or:

(created_at, customer_id, status)

Each index has a particular structure and is most useful for certain query patterns.

For our query:

WHERE customer_id = 18472
  AND status = 'completed'
ORDER BY created_at DESC

the index:

(customer_id, status, created_at)

matches the query structure very well.


The Leftmost Prefix Principle

One of the most important concepts when working with composite indexes is the leftmost prefix.

Given:

INDEX (customer_id, status, created_at)

MySQL can efficiently use the index for queries involving:

customer_id

or:

customer_id + status

or:

customer_id + status + created_at

But an index beginning with customer_id is generally not a direct substitute for an index beginning with status when the query only filters by status.

For example:

WHERE customer_id = 18472

Good fit.

WHERE customer_id = 18472
AND status = 'completed'

Even better.

But:

WHERE status = 'completed'

doesn’t get the same benefit from the index because customer_id is the first indexed column.

This is why blindly adding columns to indexes isn’t good database engineering.


Indexes Are Not Free

At this point, someone usually asks:

“Why not index every column?”

Because indexes have a cost.

Every index consumes storage.

And whenever you insert or update a row, MySQL may need to update the relevant indexes.

Imagine a table with:

2.5 million rows

and five indexes.

Now every insert potentially involves maintaining multiple index structures.

So indexes create a trade-off:

BenefitCost
Faster readsMore disk space
Faster filteringSlower writes
Faster sortingMore maintenance
Better query performanceMore memory pressure
Faster lookupsMore complex schema

The goal isn’t:

“Create as many indexes as possible.”

The goal is:

Create the indexes that support the queries your application actually runs.


A Common Mistake: Indexing Every Column Separately

Consider this:

CREATE INDEX idx_customer
ON orders (customer_id);

CREATE INDEX idx_status
ON orders (status);

CREATE INDEX idx_created
ON orders (created_at);

At first glance, this looks reasonable.

But our query uses all three:

WHERE customer_id = 18472
AND status = 'completed'
ORDER BY created_at DESC

Three individual indexes aren’t necessarily equivalent to one well-designed composite index:

CREATE INDEX idx_customer_status_created
ON orders (customer_id, status, created_at);

The composite index can represent the query’s access pattern much more directly.

This doesn’t mean composite indexes are always better.

It means the index should be designed around the workload.


Selectivity Matters

Another important concept is selectivity.

Imagine a table with 2.5 million orders.

Suppose:

customer_id

has hundreds of thousands of distinct values.

That’s potentially highly selective.

But:

status

might contain only:

pending
completed
cancelled
failed

Only four values.

An index on status alone may not be particularly selective.

For example:

WHERE status = 'completed'

could potentially match a huge percentage of the table.

An index doesn’t automatically make every query fast.

The usefulness of an index depends on the data distribution and the query.


The Query Planner Makes the Decision

MySQL doesn’t blindly use an index just because one exists.

It has an optimizer.

The optimizer considers different possible execution strategies and estimates their cost.

For example:

Option A
--------
Full table scan
2,500,000 rows


Option B
--------
Use index
Estimated 10 rows

Option B is obviously attractive.

But sometimes the optimizer may decide that an index isn’t worth using.

For example, if a query matches a huge portion of the table, scanning the table sequentially can sometimes be cheaper than performing many random lookups.

That’s why:

EXPLAIN

is so important.

Don’t guess.

Look at the execution plan.


What About ORDER BY?

Our query didn’t just filter rows.

It also had:

ORDER BY created_at DESC

This matters.

Suppose MySQL finds 50,000 matching orders.

It then needs the latest 10.

If the rows aren’t already available in the required order, MySQL may have to perform additional sorting work.

That’s where you might see:

Using filesort

in the execution plan.

Despite the name, filesort doesn’t necessarily mean MySQL literally writes everything to disk.

It’s MySQL’s name for an additional sorting algorithm.

The important point is:

Sorting can be expensive when the database has a large set of rows to sort.

A well-designed index can sometimes reduce or eliminate that work.


Why LIMIT Doesn’t Save You

This deserves repeating.

Consider:

SELECT *
FROM orders
WHERE status = 'completed'
ORDER BY created_at DESC
LIMIT 10;

You might think:

“Only 10 rows are returned, so it must be fast.”

Not necessarily.

Imagine 2.5 million rows where 1.8 million have:

status = completed

MySQL may still have a huge amount of work to do.

Now compare that with an index that allows MySQL to walk directly through the relevant records in the required order.

The difference can be dramatic.


A More Realistic Example

Imagine an analytics application storing user activity.

CREATE TABLE user_events (
    id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    user_id BIGINT UNSIGNED NOT NULL,
    event_type VARCHAR(50) NOT NULL,
    created_at DATETIME NOT NULL,
    metadata JSON
);

The table contains:

2,500,000 rows

The application frequently runs:

SELECT id, event_type, created_at
FROM user_events
WHERE user_id = 92831
ORDER BY created_at DESC
LIMIT 10;

Without an appropriate index:

2,500,000 rows
        ↓
search for user_id
        ↓
sort matching records
        ↓
return 10

With:

CREATE INDEX idx_user_events_user_created
ON user_events (user_id, created_at DESC);

the database has a much more efficient path:

user_id = 92831
        ↓
jump into index
        ↓
walk newest records
        ↓
stop after 10

That’s the kind of optimization that scales.


The Difference Between “Fast Enough” and “Scalable”

Suppose a query takes:

800 ms

when the table contains 2.5 million rows.

Maybe that’s acceptable today.

But what happens at 25 million rows?

If the query’s work grows roughly with the table size, you could eventually have:

2.5 million → 800 ms
25 million  → several seconds

Now imagine the application runs that query hundreds of times per second.

The database becomes overloaded.

This is why database optimization isn’t only about making today’s query faster.

It’s about reducing how the cost of the query grows as the data grows.


The Server Upgrade Trap

When a database becomes slow, upgrading hardware is tempting.

For example:

Before

4 CPU
8 GB RAM
SSD

becomes:

After

16 CPU
64 GB RAM
NVMe

And perhaps the query becomes faster.

But if the query still scans 2.5 million rows, you’ve only made the expensive operation somewhat faster.

You’re still doing unnecessary work.

If the application eventually grows to 25 million rows, the problem comes back.

Hardware can be important.

But hardware should not be used to compensate for inefficient database access patterns.


Fix the Work Before Adding More Hardware

Think about it this way.

Suppose you have a warehouse containing 2.5 million boxes.

You need one specific box.

There are two approaches.

Approach 1: Bigger forklift

Buy a faster forklift.

Approach 2: Organize the warehouse

Put the boxes into labeled sections so you can go directly to the correct location.

The second approach reduces the amount of work.

That’s what a good index does.

The database doesn’t necessarily need more power.

It needs better directions.


Measuring the Improvement

When optimizing a query, don’t rely only on intuition.

Measure it.

Before:

MetricBefore
Rows in table2,500,000
Rows examined~2,500,000
Rows returned10
Execution time1.8 seconds

After:

MetricAfter
Rows in table2,500,000
Rows examined~10
Rows returned10
Execution time5 ms

The exact numbers will vary depending on hardware, cache state, MySQL version, schema, data distribution, and workload.

But the important improvement is the reduction in work.

2,500,000
    ↓
10

That’s not a small optimization.

That’s a completely different execution strategy.


But Be Careful With “Rows Examined”

Even this metric needs context.

Depending on the query and execution plan, the number of rows MySQL examines can be different from the number of rows ultimately returned.

For example:

Rows examined: 10,000
Rows returned: 10

isn’t necessarily terrible.

It depends on the query.

The goal isn’t always:

“Make rows examined equal rows returned.”

The goal is:

Make MySQL do the smallest reasonable amount of work for the workload.


Covering Indexes: Another Level of Optimization

There is another interesting technique called a covering index.

Suppose our query is:

SELECT user_id, event_type, created_at
FROM user_events
WHERE user_id = 92831
ORDER BY created_at DESC
LIMIT 10;

And our index is:

CREATE INDEX idx_user_events_covering
ON user_events (user_id, created_at, event_type);

The index contains all the columns needed by the query.

In some cases, MySQL can satisfy the query directly from the index without having to fetch the full table rows.

That’s potentially a significant optimization.

But again, don’t automatically create huge covering indexes everywhere.

Larger indexes consume more storage and make writes more expensive.

Use them where the workload justifies them.


Don’t Add an Index Without Checking Existing Ones

Before creating an index, inspect the table:

SHOW INDEX FROM orders;

You may already have something like:

PRIMARY (id)
idx_customer (customer_id)
idx_customer_status (customer_id, status)

Creating:

(customer_id, status, created_at)

might be useful.

But depending on the workload, some existing indexes may become redundant.

Indexes should be reviewed as a set.


Indexes Should Follow Real Queries

A database schema shouldn’t be designed only around what the data looks like.

It should also be designed around how the application accesses that data.

For example, suppose your application frequently executes:

WHERE customer_id = ?
AND status = ?
ORDER BY created_at DESC
LIMIT 10

That’s a strong signal for an index designed around that access pattern.

But if another application mostly executes:

WHERE email = ?

then the appropriate index is completely different:

CREATE UNIQUE INDEX idx_users_email
ON users (email);

There is no universal “best index.”

There is only:

the right index for a particular workload.


A Practical Indexing Workflow

When we encounter a slow query, a useful workflow is:

1. Find the actual query

Don’t optimize based on assumptions.

Get the SQL that is actually running.

2. Measure it

Look at:

Execution time
Rows examined
Rows returned
Frequency

3. Run EXPLAIN

EXPLAIN SELECT ...;

4. Look for expensive access patterns

Especially:

ALL
Large row estimates
Large scans
Filesort
Temporary tables

5. Check existing indexes

SHOW INDEX FROM table_name;

6. Design an index around the query

Consider:

WHERE
JOIN
ORDER BY
GROUP BY
SELECT

7. Test the new plan

Run:

EXPLAIN

again.

For deeper testing:

EXPLAIN ANALYZE

8. Measure the real application

A query can look good in isolation but behave differently under production load.

9. Monitor after deployment

Make sure the optimization actually improves the workload.


One Index Can Change the Entire System

This is the part people often miss.

A slow query doesn’t only affect that query.

Imagine the application receives:

100 requests/second

and each request executes a query that scans millions of rows.

The database is doing enormous amounts of unnecessary work.

That can lead to:

High CPU
    ↓
Longer query times
    ↓
More concurrent queries
    ↓
More CPU usage
    ↓
Connection buildup
    ↓
Application timeouts

It’s a feedback loop.

Now optimize the query.

Instead of scanning millions of rows, the database finds the required records almost immediately.

The database spends less CPU time.

Queries finish faster.

Connections are released faster.

The application can handle more traffic.

One index can therefore improve more than one query.

It can change the behavior of the entire application.


The Most Important Lesson

The biggest lesson wasn’t:

“Indexes make queries faster.”

Everyone knows that.

The real lesson was:

Performance is often about reducing work, not adding resources.

We had an older e-commerce platform with a table containing roughly:

2,500,000 rows

The application wanted:

10 rows

Our first instinct could have been:

More RAM?
More CPU?
Faster disk?
Bigger server?

But the database didn’t need more resources.

It needed a better access path.

After designing the index around the actual query, MySQL could locate the relevant records without walking through the entire table.

The difference was dramatic.

Before

2,500,000 rows
████████████████████████████████████████

After

10 rows
█

Same server.

Same database.

Same data.

Same application.

Different execution plan.


Final Thoughts

At CodeROG, one of the things we often see when working with older production systems is that performance problems aren’t always caused by insufficient hardware.

Sometimes the system has simply outgrown the assumptions under which it was originally built.

A query that was perfectly acceptable when a table contained 50,000 rows can become a serious problem when that same table reaches 2.5 million rows.

That’s why performance tuning should start with measurement.

Don’t immediately increase server capacity.

Don’t randomly add indexes.

Don’t assume LIMIT 10 means MySQL only processes 10 rows.

Instead:

Find the slow query
        ↓
EXPLAIN it
        ↓
Understand the execution plan
        ↓
Check the indexes
        ↓
Design the right index
        ↓
Measure again

The difference between a database that struggles with millions of rows and one that handles them comfortably isn’t always more hardware.

Sometimes it’s one carefully designed index.

We didn’t upgrade the server.

We fixed the query.


A CodeROG Engineering Lesson

This was one of those optimizations that looks almost too simple after you understand the problem.

There was no database migration to a new platform.

No server replacement.

No massive rewrite of the e-commerce application.

No expensive infrastructure upgrade.

We found where the database was spending its time, understood why it was doing that work, and gave MySQL a much better path to the data.

That is often what good performance engineering looks like.

Measure first. Understand the workload. Fix the bottleneck. Then decide whether you actually need more hardware.

— CodeROG Insights

Need a hand with this?

Let our engineers take it from here