A database can work perfectly well for months and then suddenly become a problem as the application grows. Pages that once loaded instantly start taking several seconds. Reports become slower to generate, and users begin noticing delays when searching or filtering records.
This is a familiar situation in applications that handle a growing amount of data. The first reaction is often to increase server resources or upgrade the database instance. Sometimes that helps, but it does not necessarily solve the underlying problem.
In many cases, MySQL is spending too much time finding, reading, or processing records because the queries and indexes were not designed with the growing dataset in mind.
The good news is that a few carefully chosen changes can make a noticeable difference. The important part is knowing what to look for before changing anything.
Let's walk through some practical ways to approach MySQL query optimization.
1. Start by Finding Out Why a Query Is Slow
When a query takes several seconds to execute, resist the temptation to start adding indexes immediately. First, find out what MySQL is actually doing.
There are several possible reasons for slow execution. The database might be scanning more records than necessary, using an unsuitable index, processing an expensive JOIN, or performing a large sort operation. Sometimes the SQL is perfectly reasonable, but the database server does not have enough resources to handle the workload efficiently.
The EXPLAIN statement is a good starting point.
Consider a simple query:
EXPLAIN
SELECT *
FROM patient
WHERE hospital_id = 10
AND type = 'IPD';
The execution plan shows how MySQL intends to retrieve the matching records. Pay attention to the access type, possible keys, selected key and estimated number of rows.
For a deeper look, MySQL 8.4 also supports EXPLAIN ANALYZE.
EXPLAIN ANALYZE
SELECT *
FROM patient
WHERE hospital_id = 10
AND type = 'IPD';
This runs the query and provides actual execution information, including iterator timing and row counts. It is particularly useful when the optimizer's estimates do not match what happens during execution.
I usually prefer examining the execution plan before changing the SQL. Otherwise, it is easy to spend time fixing something that was never the real bottleneck.
One caution: EXPLAIN ANALYZE executes the statement. Be particularly careful when using it with expensive queries against production data.
2. Choose Indexes Based on How Your Application Queries Data
Indexes are essential when working with large MySQL tables, but adding more indexes does not automatically make a database faster.
Imagine an application that stores patient records for multiple hospitals. A user selects a hospital and expects to see only records belonging to that hospital.
Without a suitable index, MySQL may have to examine a large number of records before finding the required results.
A simple index can help:
CREATE INDEX idx_patient_hospital
ON patient(hospital_id);
Now MySQL has an index it can consider when filtering records by hospital_id.
However, the interesting part comes when applications start combining multiple conditions.
For example, a reporting screen might filter records by hospital, patient type and status. Creating an individual index for every column may not be the most effective approach.
Before creating an index, look at the queries your application executes regularly. Consider how frequently they run, which columns appear in their WHERE clauses, and whether existing indexes already cover those access patterns.
An index should solve a real query problem. Otherwise, it simply adds storage requirements and makes data modifications more expensive.
3. Understand Why Composite Indexes Are Useful
One area that deserves particular attention is composite indexing.
Consider this reporting query:
SELECT status, COUNT(*)
FROM patient
WHERE hospital_id = 10
AND type = 'IPD'
GROUP BY status;
The query needs to identify records belonging to a particular hospital and patient type, then count them according to status.
An index on just hospital_id might help, but MySQL may still need to process additional records to satisfy the remaining conditions.
A composite index can be more useful here:
CREATE INDEX idx_patient_hospital_type_status
ON patient(hospital_id, type, status);
The column order is important.
MySQL can use the leftmost prefixes of this index. That means it can potentially support searches using hospital_id, searches using both hospital_id and type, and searches involving all three columns.
It cannot generally use the same index for an efficient direct lookup on type alone because hospital_id comes first.
This is why I would not recommend creating composite indexes simply by looking at the columns in a table. Look at the actual queries first.
For queries with equality conditions followed by range conditions, a common starting point is to place the equality-filtered columns first. The best arrangement still depends on the complete query, selectivity and ordering requirements, so always verify it with EXPLAIN.
There is another detail worth remembering: indexes are not free. Every additional index needs storage and must be maintained when records are inserted, updated or deleted.
The objective is not to create as many indexes as possible. It is to create the few indexes that support the queries that matter.
4. Stop Retrieving Data Your Application Does Not Need
A surprisingly common problem is retrieving entire records when the application only needs two or three columns.
For example:
SELECT *
FROM patient
WHERE hospital_id = 10;
If the screen only displays an ID, status and creation date, retrieving every column is unnecessary.
A narrower query is easier to work with:
SELECT id, status, created_at
FROM patient
WHERE hospital_id = 10;
This can reduce the amount of data MySQL reads and sends to the application. With a suitable covering index, it may also avoid additional table lookups.
Pagination deserves similar attention.
Many applications use LIMIT and OFFSET to implement pagination. This works well for smaller result sets, but large offsets can become expensive because MySQL still needs to work through rows that will eventually be discarded.
For example:
SELECT id, status, created_at
FROM patient
WHERE hospital_id = 10
ORDER BY id
LIMIT 50 OFFSET 50000;
For applications where users move through records sequentially, keyset pagination is often a better alternative:
SELECT id, status, created_at
FROM patient
WHERE hospital_id = 10
AND id > 50000
ORDER BY id
LIMIT 50;
This approach uses the last seen ID as the starting point for the next page. The ID must be an appropriate indexed navigation key, and the cursor logic must match the requested ordering.
It is a small change at the SQL level, but it can make a significant difference when users navigate deep into large datasets.
5. Pay Attention to JOIN and GROUP BY Operations
Reporting queries are often more complicated than ordinary application queries. They might combine several tables, calculate totals and group results by different categories.
This is where inefficient JOIN conditions and aggregation can become expensive.
Consider the following example:
SELECT h.name, COUNT(p.id)
FROM hospital h
JOIN patient p
ON p.hospital_id = h.id
GROUP BY h.name;
Before trying to rewrite this query, check whether the JOIN columns are indexed appropriately.
Also check that both columns use compatible data types. For example, joining an integer column to a string column can introduce unnecessary conversion work and affect index usage.
GROUP BY operations also deserve attention. An index that supports the filtering and grouping pattern may help, but the optimizer still needs to decide whether using it is worthwhile.
There is no universal index that makes every aggregation query fast.
For reports that repeatedly calculate the same totals across large datasets, consider whether the application really needs to calculate everything from the original tables every time.
A summary table or periodically updated aggregate can sometimes be a better solution. This introduces additional maintenance work and potentially some delay in reporting data, so it makes sense only when the reporting requirements justify it.
6. Do Not Ignore the Database Server
Even well-written queries can struggle when the database server is under-resourced.
In MySQL, the InnoDB buffer pool plays an important role. It keeps frequently accessed table and index pages in memory, reducing the need to read them repeatedly from storage.
When reviewing a slow database, I would look at more than just CPU and RAM usage.
Some useful areas to monitor include:
- InnoDB buffer pool activity and read requests.
- Physical disk reads and writes.
- Slow query frequency and execution time.
- Active connections and connection pressure.
- Lock waits and long-running transactions.
- CPU and memory utilization.
For example, a database server with a relatively small buffer pool may struggle with a workload that repeatedly accesses data spread across many tables and indexes.
Increasing innodb_buffer_pool_size can help in the right circumstances, but it needs to be planned around the memory available to the entire server.
Likewise, upgrading the database instance may be necessary when the workload has genuinely outgrown the existing infrastructure. It should not be the first response to every slow query.
I would rather understand why a query is consuming resources before recommending a hardware upgrade.
7. Measure the Improvement Instead of Assuming It
One database optimization exercise I worked on involved a patient database containing approximately 502,750 records across 35 hospitals.
A reporting query was taking around 7.76 seconds to execute. The database was examining approximately 30,617 rows, and the server had limited resources.
The first step was to look at the query and understand how it filtered and grouped patient records. Since hospital ID, patient type and status were frequently involved in the reporting conditions, a composite index was introduced:
CREATE INDEX idx_patient_hospital_type_status
ON patient(hospital_id, type, status);
The important lesson from this exercise was not simply that adding an index solves slow queries. It was that index design needs to reflect how the application actually uses its data.
The figures above describe the workload before evaluating the change; they should not be interpreted as a measured improvement. A proper before-and-after comparison is necessary to establish the impact.
When evaluating an optimization, I recommend recording:
- Execution time before and after the change.
- Rows examined and rows returned.
- Changes in the execution plan.
- CPU and disk activity.
- Any impact on INSERT, UPDATE and DELETE operations.
Testing under similar conditions is important. A query may appear faster during a quiet period but behave differently when multiple users access the application simultaneously.
Make one meaningful change at a time and measure the result. This makes it much easier to understand which change actually helped.
Conclusion
Working with large MySQL datasets is not just about having more powerful database servers. It is about making sure the database is doing only the work it needs to do.
Start with the execution plan rather than guessing. Review the queries your application runs most frequently, build indexes around their actual filtering conditions, and avoid retrieving unnecessary data. Give JOIN and GROUP BY operations the same attention as ordinary SELECT statements.
Also remember that an optimization that improves read performance may introduce additional write overhead. Every change needs to be evaluated against the application's complete workload.
Most importantly, measure the result. A well-chosen index or a simpler query can sometimes achieve more than an infrastructure upgrade.
The best approach is to understand the bottleneck first, make a targeted change, and verify that it genuinely improves the application.
Sources and Further Reading
- MySQL 8.4 Reference Manual: Optimization and Indexes
- MySQL 8.4 Reference Manual: Multiple-Column Indexes
- MySQL 8.4 Reference Manual: EXPLAIN Statement