DEV Community

Furqan Ashraf
Furqan Ashraf

Posted on

Stop Guessing Why Your SQL Query Is Slow: A Simple Guide to EXPLAIN


If you are just getting started with SQL, you have probably written a query that worked fine while testing, but felt slow once the table had more data in it. This happens to almost everyone, and it does not mean you did something wrong. It usually just means the database is not being used in the most efficient way yet, and that is a normal part of learning.

This article walks through how to understand why a query might be slow, in simple terms, without needing to be an expert.

First, understand what the database is actually doing

When you write a query, you might imagine the database just "looks through the table" to find the data. In a way, that is true, but there is more to it. Before running your query, the database makes a small decision internally: how should it go through the table to find what you asked for? Should it check every single row, or is there a faster shortcut it can use?

That decision is what really controls how fast or slow your query feels. Two queries that look almost the same can behave very differently depending on this.

The good news is you do not have to guess. Most databases let you ask them directly what they plan to do, before actually running the query. In MySQL and PostgreSQL, you do this by adding the word EXPLAIN in front of your query:

EXPLAIN SELECT customer_id, total_amount
FROM orders
WHERE status = 'pending';
Enter fullscreen mode Exit fullscreen mode

This will not return your actual data. Instead, it shows you the plan, almost like a summary of what the database is about to do. You do not need to understand every detail of this output right away. Just look for one simple thing: is the database checking every row in the table, or is it jumping straight to the rows that match?

If your table only has a few hundred rows, checking every row is usually fine and you will not notice any delay. But once a table grows to thousands or millions of rows, checking every single row becomes slow, and that is usually the real reason behind a slow query.

What an index actually does (in simple terms)

You have probably heard the word "index" mentioned around database performance. An index works a bit like the index page at the back of a textbook. Instead of flipping through every page to find a topic, you check the index page, and it tells you exactly where to look.

A database index works the same way. Instead of scanning the whole table, the database can jump straight to the matching rows if there is an index on the right column.

For example, if you often search orders by their status:

CREATE INDEX idx_status ON orders(status);
Enter fullscreen mode Exit fullscreen mode

This tells the database to keep a quick lookup list for that column, so future searches on status do not need to scan the entire table.

One important tip: an index only helps if your query searches using that exact column in a simple way. If you wrap the column inside a function, like checking only the year from a date column, the database usually cannot use the index anymore, even if one exists. It is better to compare the raw column directly whenever possible.

Also, indexes are not something you should add to every column "just in case." They do help with reading data faster, but they slightly slow down adding or updating data, since the database has to update the index too. For now, it is enough to know this trade-off exists. You will get a feel for when to use indexes as you write more queries.

A few simple habits that make a real difference

You do not need advanced tricks to write faster queries. A few small habits go a long way, especially while you are still learning.

Only ask for the columns you actually need. It is common to write SELECT * out of convenience. This asks the database for every single column, even ones you might not use. Once you know which columns you actually need, it is better to name them directly:

SELECT name, email FROM customers;
Enter fullscreen mode Exit fullscreen mode

This is lighter for the database and easier to read too.

Avoid pulling more rows than you will show. If you are only displaying twenty results on a page, there is no need to ask the database for thousands of rows and filter them later in your code. Use LIMIT to ask the database to only return what you need:

SELECT * FROM articles LIMIT 20;
Enter fullscreen mode Exit fullscreen mode

Be careful with pagination on large tables. A common approach when starting out is something like LIMIT 50000, 20, meaning "skip fifty thousand rows, then give me the next twenty." The problem is the database still has to go through those fifty thousand rows first, even though you do not want them. As your data grows, this gets noticeably slower.

A simpler and faster habit is to filter using the last row you already saw, instead of skipping by a number. For example, instead of:

SELECT * FROM posts
ORDER BY id
LIMIT 50000, 20;
Enter fullscreen mode Exit fullscreen mode

track the last ID you saw on the previous page, then do this:

SELECT * FROM posts
WHERE id > 5000
ORDER BY id
LIMIT 20;
Enter fullscreen mode Exit fullscreen mode

The database can jump straight to id > 5000 using the index, instead of counting through 50,000 rows first just to skip them. The same idea works with a timestamp column too, if you are paginating by date instead of ID.

None of these habits require deep expertise. They are just small choices that matter more as your tables grow bigger.

Query speed is something you check now and then, not just once

When you are still new to this, it is easy to think performance is something you fix one time and forget about. In reality, a query that runs fine today might feel slow months later, simply because the table has grown. This is completely normal, and experienced developers deal with the same thing.

A good habit going forward is this: whenever a query feels slower than expected, run EXPLAIN on it first before changing anything. It takes the guesswork out of the process and shows you exactly where the slowdown is coming from.

If you are still building your SQL foundations and want a simple, step by step place to start, APIFreaks has a free SQL tutorial series that covers the basics in order, from what a table is, all the way through joins, subqueries, and views. It is a good next stop before diving deeper into topics like performance and optimization.

Top comments (0)