Database Performance: Indexing Strategies and Query Optimization

In early February, one of our clients called, and we could hear the panic in his voice. The sales report in the admin panel was taking forty seconds to open, the accounting team couldn't get their morning report, and the hosting company had come back with an offer to "upgrade the server." We connected and took a look: an orders table with three million rows, and not a single index on the two columns the report filtered on. We added one composite index, and the query went from forty seconds to three hundred milliseconds. Same server, same code.

The interesting part of this story is that it isn't an exception. In projects we take over, the first place we look is the database, because experience tells us this: if the application is slow, nine times out of ten the culprit is the database, and if the database is slow, the culprit is almost always a missing or poorly designed index. And more often than not, a single day of index work delivers more speed than an "optimization project" dragging on for months.

The index at the back of the book

When I explain how indexes work, I always use the same analogy: you're looking for the term "circuit breaker" in a thick book. You can either flip through it page by page (in database terms, that's called a full table scan) or check the index at the back of the book and go straight to page 214. A database index is exactly that: instead of scanning millions of rows, the engine reaches its target in a few steps through a sorted structure (usually a B-tree).

There's another side to the coin, too. Every index means a write cost: when an INSERT or UPDATE hits the table, all the relevant indexes are updated. Writing a record to a table with twenty indexes is like a book that reprints its index after every sentence. That's why the "index every column" approach is as harmful as having no indexes at all; the art lies in striking the balance between read gains and write costs.

Without an index the engine scans every row; with an index it reaches the target through a B-tree, but every index also brings a write cost.
The art is striking the balance between read gains and write costs.

There's a step beyond that as well: if all the columns a query needs are inside the index, the engine never goes to the table at all and returns the answer straight from the index. This is called a covering index, and for narrow queries that run frequently (something like "this user's last twenty order numbers and dates") the difference is noticeable. Of course, you don't create a covering index for every query, but for one or two critical queries that run hundreds of thousands of times a day, it's worth considering.

Which column deserves an index?

We have a simple rule of thumb from the field: columns that appear in a query's WHERE condition, JOIN clause and ORDER BY expression are index candidates; what's written in the SELECT list has nothing to do with the indexing decision. It still surprises me how often such a simple rule is applied wrong: we see projects where ten columns visible in the SELECT have been indexed, while the actual filter column in the WHERE has been left bare.

Selectivity has to be taken into account too. Indexing a column like "gender," which takes only two or three values, on its own yields little; the engine will still read half the table. On the other hand, nearly unique columns such as customer number, email or order code are where an index works most efficiently. On write-heavy tables (logs, events, measurement data), think twice about every index; each one you add there eats into your records-per-second capacity.

ORDER BY is also within an index's job description, and that often gets forgotten. If the sort can't be satisfied by a suitable index, the engine sorts the result set in memory (or on disk if memory isn't enough); that's what shows up as "filesort" in EXPLAIN output. On a small result set it doesn't matter, but for queries of the "twenty most recent records" type, the right index gives you sorting for free: the engine simply reads the first twenty rows from the already sorted structure and stops.

Index candidates: WHERE conditions, JOIN clauses, ORDER BY expressions and columns with high selectivity; the SELECT list doesn't affect the decision.
Columns in the SELECT list have nothing to do with the indexing decision.

The math of column order in a composite index

The real performance leaps usually come from composite indexes, and here column order is everything. Let's go back to the report example from the beginning: the query filtered with "status = 'completed' AND date >= X". An index ordered as (status, date) makes this query fly, quite literally: the engine first descends to the status branch, then reads the date range in order. The same index won't work for a query that asks only "date >= X," because you can't search a phone book by first name without knowing the last name; the phone book is sorted by last name.

The practical rule is this: the column filtered by equality and with high selectivity goes first, the column used for a range scan goes last. This one sentence solves most of the composite index mistakes we see in the field.

Ways of writing queries that silently disable an index

The sneakiest situation is an index that exists but isn't used; nobody sees an error, everything is just slow. The classic example is using a function: the moment you write WHERE YEAR(date) = 2024, the engine has to apply the function to every row and the index is out of play. Write the same query as a range instead, date >= '2024-01-01' AND date < '2025-01-01', and the index is back in the game. The LIKE '%word%' pattern is similar; the leading wildcard makes the sorted structure of the index meaningless. If you genuinely need to search within text, the right tool is a FULLTEXT index or a separate search engine such as Elasticsearch.

Then there's the type mismatch trap, which we learned about the hard way last year on a vehicle tracking project. The license plate column was VARCHAR, but the application was sending a number in the query; MySQL was performing an implicit type conversion on every row, and the index was effectively ignored. A one-character fix (adding quotes to the query) brought the query time down from seconds to milliseconds. (Mistakes like this are invisible in code review; they can only be caught by measurement.)

A separate note for teams using an ORM: not seeing SQL in your code doesn't mean SQL isn't being generated. In teams that have never read the queries their ORM produces, we run into two classic findings: the N+1 pattern, which fires queries one by one inside a loop, and auto-generated WHERE conditions that don't fit any index. In the development environment, with a hundred-row table, everything runs at the speed of light; the problems start when it meets three million rows. Don't talk about performance until your test data is realistically sized.

Don't touch anything before reading EXPLAIN

So how do you know which query is the problem? Not by intuition. Intuition is a bad advisor in this business; the query everyone thinks is slow is often innocent, and the real culprit is the "fast" query that runs ten thousand times a day.

Two tools are enough. The first is EXPLAIN: put it in front of the query you suspect and look at the output. If you see "type: ALL," there's a full table scan; the "rows" column tells you how many rows the engine plans to scan. If you see "rows: 2.8M" on a million-row table and say "but we have an index," then your index doesn't fit that query. The second is the slow query log: set long_query_time to 1 second, collect data for a week, then start with the queries that run most often and consume the most time in total. Getting the hang of these two tools takes half a day; in most projects, the payoff exceeds that of a hardware investment.

The slow query log is turned on, data is collected for a week, the query consuming the most time is selected and examined with EXPLAIN.
Proceed by measurement, not intuition.

One last reminder: index work isn't a one-time job. Applications evolve, queries change, and an index that was once vital becomes an orphan, but it keeps generating write costs. Auditing and removing unused indexes once a year is as legitimate a maintenance item as adding new ones. Think of the database as a living system, not a box you configure once and forget.

You don't have to live with a forty-second report screen. If you have a similar slowdown story, get in touch with us; more often than not, the diagnosis turns out to be a day's work and gets solved without touching the server bill.