Laravel Development
Your Laravel App Is Slow Even With Few Queries? Find the Missing Database Indexes
Your Laravel application may execute only a handful of queries and still feel slow. Missing database indexes can force MySQL to scan thousands of rows unnecessarily. Learn how to inspect slow queries with EXPLAIN, create the right indexes through Laravel migrations, and avoid common indexing mistakes.
Laravel Development
Your Laravel App Is Slow Even With Few Queries? Find the Missing Database IndexesYour Laravel application may execute only a handful of queries and still feel slow. Missing database indexes can force MySQL to scan thousands of rows unnecessarily. Learn how to inspect slow queries, create useful indexes, and avoid common indexing mistakes.
The problem: fewer queries do not always mean a faster application
You have already optimized your Laravel application. You removed unnecessary queries, eager-loaded relationships, and reduced repeated database calls. But one API endpoint still takes several seconds to return.
The problem may not be the number of queries. It may be the amount of data MySQL has to examine to answer each query.
Imagine a users table containing 500,000 records. Your application frequently searches for a user by email:
SELECT * FROM users
WHERE email = 'developer@example.com';
Without a suitable index, the database may need to examine a large number of rows to find the matching email. An index gives the database a more efficient way to locate matching records.
This is why database indexing is one of the most important skills for developers building production Laravel applications.
1. What is a database index?
A database index is a data structure that helps the database find records without scanning the entire table for every lookup. You can think of it like the index at the back of a book: instead of reading every page, you use the index to find the relevant location.
MySQL commonly uses B-tree indexes for ordinary primary, unique, and secondary indexes. They can help with filtering, joins, and certain sorting operations.
For example, an index on the email column can make this lookup more efficient:
SELECT id, name, email
FROM users
WHERE email = 'developer@example.com';
However, indexes are not free. They consume storage and must be maintained when rows are inserted, updated, or deleted. Adding an index to every column is not a good optimization strategy.
2. Find the slow query before changing anything
Do not guess which columns need indexes. Start by identifying the actual slow query and understanding how the database executes it.
Suppose your Laravel application frequently runs this query:
SELECT id, name, email
FROM users
WHERE status = 'active'
ORDER BY created_at DESC
LIMIT 20;
You can inspect the MySQL execution plan by running:
EXPLAIN
SELECT id, name, email
FROM users
WHERE status = 'active'
ORDER BY created_at DESC
LIMIT 20;
MySQL's EXPLAIN command shows how the optimizer plans to execute the query. It provides information about
table access, candidate indexes, selected indexes, estimated rows, and other execution details.
Look at fields such as type, possible_keys, key, rows, and Extra.
A full table scan can be a warning sign on a large table, but it is not automatically bad for a small table or a query
that needs most of the records.
3. Create an index using a Laravel migration
Laravel migrations provide a clean and repeatable way to manage database indexes across development, staging, and production.
Create a migration:
php artisan make:migration add_email_index_to_users_table
Add the index in the migration:
use Illuminate\\Database\\Migrations\\Migration;
use Illuminate\\Database\\Schema\\Blueprint;
use Illuminate\\Support\\Facades\\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->index('email');
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropIndex(['email']);
});
}
};
Run the migration:
php artisan migrate
If email addresses must be unique in your application, consider a unique index instead:
$table->unique('email');
Only add a unique constraint if the business rule genuinely requires unique values. Check existing duplicate data before applying it to a production table.
4. Understand composite indexes
A common mistake is creating separate indexes for every column used in a query. Sometimes a composite index is more useful.
Consider this query:
SELECT id, title, created_at
FROM posts
WHERE status = 'published'
AND category_id = 5
ORDER BY created_at DESC
LIMIT 20;
A composite index can be created for the columns used by this query:
Schema::table('posts', function (Blueprint $table) {
$table->index(
['status', 'category_id', 'created_at'],
'posts_status_category_created_index'
);
});
Column order matters. MySQL can generally use the leftmost prefix of a composite B-tree index.
An index on (status, category_id, created_at) can support lookups beginning with
status, or with both status and category_id.
It is not equivalent to having an index on every possible combination of those columns.
The best order depends on your real query patterns, filtering conditions, selectivity, sorting, and database optimizer.
Verify the result with EXPLAIN instead of assuming the index will be used.
5. Index foreign keys and join columns thoughtfully
Laravel applications frequently join tables through relationships. For example, an order belongs to a customer:
SELECT orders.id, orders.total, users.name
FROM orders
JOIN users ON users.id = orders.user_id
WHERE orders.user_id = 25;
An index on the referencing column can help the database find related orders efficiently:
$table->foreignId('user_id')
->constrained()
->index();
Review the actual schema before adding another index. Some database definitions and migration patterns already create indexes or constraints, and a duplicate index is usually unnecessary.
6. Avoid common indexing mistakes
Indexing every column
Every additional index takes storage and adds work to write operations. Add indexes that support real queries, not every column that might be searched someday.
Ignoring column order
Composite indexes are order-sensitive. Design them around the query patterns you need to support.
Using functions on indexed columns without checking the plan
A condition such as WHERE DATE(created_at) = '2026-12-01' may prevent an ordinary index on
created_at from being used as efficiently as a range condition. Consider rewriting it:
WHERE created_at >= '2026-12-01 00:00:00'
AND created_at < '2026-12-02 00:00:00'
This can make an ordinary index more useful, depending on the data type, timezone rules, and query plan.
Assuming an index always makes a query faster
If a query reads a large percentage of a small table, a table scan may be cheaper. The optimizer decides based on available statistics and estimated costs. Measure before and after changing the schema.
7. Measure the improvement
After creating an index, run the same query again and inspect its execution plan. Compare the selected index, estimated rows, and execution time under realistic conditions.
MySQL also supports EXPLAIN ANALYZE for supported statements. Unlike ordinary EXPLAIN, it executes the
statement and reports actual iterator timing and row information. Use it carefully, especially for statements that
modify data.
EXPLAIN ANALYZE
SELECT id, name, email
FROM users
WHERE email = 'developer@example.com';
Also test the complete Laravel endpoint. Database execution is only one part of response time; application logic, network latency, serialization, and external services can contribute too.
Final thoughts
A Laravel application can have a low query count and still suffer from slow database operations. The missing piece may be an index that helps MySQL find the required rows efficiently.
Start with the slow query, inspect it using EXPLAIN, create an index that matches the actual access pattern,
and measure the result. Be especially thoughtful about composite indexes and the cost of maintaining too many indexes.
Do not add indexes blindly. Find the query, understand the execution plan, and let evidence guide the optimization.