How to Debug a Slow Database Query Without Guessing

How to Debug a Slow Database Query Without Guessing

A query that takes 8 seconds in production and 40 milliseconds on your laptop is not a mystery. It is a measurement problem. To debug a slow database query, you need evidence: what the database actually did, which rows it touched, and where the time went. Guessing means adding an index at random and hoping. A short, repeatable process beats guessing, on PostgreSQL, MySQL, and most other relational databases.

This guide walks through that process: reproduce the slowness, read the execution plan, check the usual suspects, fix the real cause, and prove the fix worked. You need the slow query itself, a way to run EXPLAIN, and ideally the slow query log. No special tools are required.

Step 1: Reproduce the Slow Query First

Before you change anything, capture the exact query from the slow query log, your application logs, or your APM tool, and run it against a copy of production data. A query against a 200-row dev database tells you nothing about one against a 2-million-row table.

Run the query twice. The first run warms the cache; the second shows the steady-state time. If the second run is fast, the problem may be a cold cache or a one-off lock, not the query itself. Write both numbers down.

Step 2: Debug a Slow Database Query With the EXPLAIN Plan

The execution plan is the single most useful piece of evidence you have. It shows how the database decided to run your query: which indexes it used, which tables it scanned, and how many rows it estimated at each step.

In PostgreSQL, run:

EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders
WHERE customer_id = 42 AND created_at > '2026-01-01'
ORDER BY created_at DESC LIMIT 20;

In MySQL, the equivalent is EXPLAIN ANALYZE with the same query.

Read the plan from the inside out and look for these red flags:

  • Seq Scan on a large table when you expected an index lookup. A sequential scan reads every row. On a small table that is fine; on a table with millions of rows it is usually the problem.
  • A big gap between estimated rows and actual rows. If the planner expected 10 rows and got 100,000, its statistics are stale. Run ANALYZE on the table and check again.
  • Nested loop joins with huge row counts on the inner side. A nested loop is fine for a few hundred rows and painful for a few hundred thousand.
  • Sort steps that spill to disk. In PostgreSQL, Sort Method: external merge Disk means the sort did not fit in memory. A missing index on the sort column is often the real cause.

Learn the four red flags above and you will catch most slow queries. For more on how indexes shape these plans, see this guide on how to write faster SQL queries with indexing basics.

Step 3: Check for a Missing Index

A missing index is the most common cause of a slow query, and the plan usually points straight at it. If the plan shows a sequential scan on a table filtered by a column with no index, that column is your first suspect.

Take this query:

SELECT id, total FROM orders WHERE customer_id = 42;

Without an index on customer_id, the database reads the whole orders table to find one customer’s rows. Adding the index changes that to a direct lookup:

CREATE INDEX idx_orders_customer_id ON orders (customer_id);

After adding an index, re-run EXPLAIN and confirm the plan changed. An index only helps if the planner actually uses it, so never skip this check. Also keep the index narrow: index the columns you filter and join on, not every column in the table. Every extra index slows down writes and takes disk space.

Composite indexes matter when a query filters on two columns together. An index on (customer_id, created_at) serves the query in Step 2 directly, while separate single-column indexes may not. Put the most selective column first.

Step 4: Look for the N+1 Query Problem

Sometimes no single query is slow. Your code runs the same fast query hundreds of times instead. This is the N+1 query problem, and it is one of the most common causes of slow pages in web apps.

It looks like this: the app loads 100 orders with one query, then loops through them and runs one extra query per order to fetch the customer name. That is 101 queries instead of 2, and each round trip adds latency. The database is barely working; the network is doing the damage. Fix it by fetching the related data in one query with a join:

SELECT o.id, o.total, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at > '2026-01-01';

How do you spot it? Turn on query logging for one request and count the queries. If you see the same query shape repeated with different IDs, you found it. If your joins are getting tangled, this visual guide to SQL joins explained with diagrams helps you pick the right join type.

Step 5: Stop Selecting Everything

SELECT * is a habit that costs real time. It pulls every column, including large text or JSON columns you never display, and it blocks covering indexes, where the index alone can answer the query.

Compare the two:

-- Slow: fetches every column, including a large notes field
SELECT * FROM orders WHERE customer_id = 42;

-- Faster: only the columns the page actually shows
SELECT id, total, created_at FROM orders WHERE customer_id = 42;

The same rule applies to LIMIT: a query without one on a list page may fetch 50,000 rows to show 20. Add the limit, and if the list is paginated, prefer keyset pagination (WHERE id > ? ORDER BY id LIMIT 20) over large OFFSET values, because the database still has to scan and discard the skipped rows.

Step 6: Watch Out for Functions on Indexed Columns

A function wrapped around an indexed column stops the database from using that index. The planner cannot look up LOWER(email) in an index built on email, so it falls back to scanning the whole table.

-- Slow: the function blocks the index on created_at
SELECT * FROM orders WHERE DATE(created_at) = '2026-11-01';

-- Faster: a range the index can use
SELECT * FROM orders
WHERE created_at >= '2026-11-01' AND created_at < '2026-11-02';

The same trap shows up with LOWER(), UPPER(), string concatenation, and arithmetic on a column. Rewrite the condition so the bare column sits on one side of the comparison.

Other quiet killers: implicit type casts, LIKE '%term%' with a leading wildcard, and OR conditions across different columns. When a query looks simple but the plan shows a full scan, check the WHERE clause for one of these first.

Step 7: Check the Slow Query Log and Server Load

If the plan looks fine and the query is still slow, the problem may sit outside the query. The slow query log shows which queries hurt database query performance in real traffic, how often they run, and whether the same query is slow for everyone or only sometimes.

In MySQL, enable it with:

SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;

In PostgreSQL, set log_min_duration_statement = 1000 to log statements slower than one second, then reload. Look for patterns: the same query at the top of the list every hour, or a burst at the same time each day, points at a scheduled job or a traffic spike rather than a bad query.

While you are there, check the server itself. A database starved of RAM, fighting for disk I/O, or running with too few connections will make even good queries slow. If your database runs on a small VPS, the tuning advice in this comparison of MySQL vs PostgreSQL tuning for limited RAM is a practical starting point, and this PostgreSQL install and hardening guide for Ubuntu covers the configuration basics that affect performance.

A checklist you can reuse

Work down this list and stop at the first step that explains the time:

  1. Reproduce the query and measure it twice.
  2. Read the EXPLAIN plan and note scans, bad row estimates, and disk sorts.
  3. Check for a missing index on the filtered or joined columns.
  4. Count the queries per request and rule out the N+1 query problem.
  5. Replace SELECT * with the columns you need and add a LIMIT.
  6. Remove functions and casts from indexed columns in the WHERE clause.
  7. Check the slow query log and server load for problems outside the query.
  8. Re-run EXPLAIN after the fix and compare timings before and after.

That last step is the one people skip, and it matters most. A fix you cannot measure is a guess with extra steps. When the plan shows an index scan instead of a sequential scan and the timing drops, you know the job is done. Keep the before and after numbers.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.