Diagnose Slow SQL Queries with EXPLAIN and Better Indexes
Use query plans, row estimates, buffer reads, and composite indexes to investigate slow SQL queries without adding indexes blindly.
TechSilo
AI-assisted and human-curated
When a SQL query is slow, adding an index is only a hypothesis. The database may already have a useful index, may estimate that a sequential scan is cheaper, or may be spending most of its time sorting, joining, or reading far more rows than expected.
A query plan gives you evidence about what the database is doing. This guide focuses on using that evidence to decide whether an index is likely to help.
Capture a representative query
Start with the exact query shape, realistic parameter values, and a data set large enough to reveal the problem. A query that is fast against a development database with 200 rows may behave very differently against a production table with millions of rows.
For PostgreSQL, inspect a read query with:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;EXPLAIN ANALYZE executes the statement and reports actual timing and row counts. Use it carefully: for statements that modify data, the statement really runs. Prefer read-only queries for this investigation, or use a safe transaction and rollback when appropriate.
Read the parts of the plan that answer your question
Look for these signals:
- Seq Scan: the database reads the table sequentially. This can be the right plan for small tables or queries that return a large share of the rows.
- Index Scan: the database uses an index to find matching entries and fetches table rows.
- Bitmap Heap Scan: PostgreSQL can combine matching row locations before visiting table pages.
- Sort: the query needs an ordering step that may be avoidable with a suitable index.
- Rows Removed by Filter: many rows were visited and then discarded by a filter.
- Buffers: shows shared blocks hit or read, helping reveal I/O pressure.
Do not treat an index scan as automatically good or a sequential scan as automatically bad. The plan must be judged against the number of rows returned, table size, cache state, and the actual latency requirement.
Check estimated rows against actual rows
A large difference between estimated and actual row counts can lead the planner to choose a poor join order or access path. In PostgreSQL, stale or insufficient statistics can contribute to bad estimates.
After a significant data change, updating statistics may help:
ANALYZE orders;For skewed data, the default statistics target may not describe the distribution well enough. Check the database documentation before changing planner settings; do not tune global values to compensate for one unexplained query.
Test a composite index against the filter and sort
For the example query, a candidate index might be:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);The leading key matches the equality filter, and the next key supports the requested ordering. Whether PostgreSQL uses it depends on selectivity, table statistics, visibility, and the cost of fetching the selected columns.
Create one candidate index in a staging environment or controlled migration, then compare the plan and buffer activity. Test representative parameter values; a query for a customer with 20 orders may behave differently from one for a customer with two million.
Check the cost outside the slow query
An index can improve one read path while making writes more expensive. Before keeping it, inspect:
- How often the table is inserted into or updated.
- Whether similar indexes already exist.
- The additional disk space required.
- Whether other queries use the index.
- Whether the query's latency improvement is meaningful to users.
Avoid creating near-identical indexes because they look useful in isolation. Keep a record of why each non-obvious index exists and which query or workload justifies it.
A repeatable tuning workflow
Capture the slow query, read its plan, identify the expensive operation, make one change, and measure again with comparable data and conditions. Keep the change only when it improves the target workload without unacceptable side effects.
For the underlying index structures and composite-key trade-offs, see [Database Indexes Explained](/blog/database-indexing-the-missing-link-mopxix4p). Query tuning is evidence-driven: the execution plan tells you where to investigate, and measurement tells you whether the fix worked.
Want to put this into practice?
Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.
Related blog posts
Console.log Alternatives for Efficient JavaScript Debugging
Use browser breakpoints, console.table, console.trace, timing APIs, and structured logs to debug without flooding production consoles.
Read postPreventing SQL Injection: Parameterized Queries and Safe Database Access
Learn how SQL injection works and how to prevent it using parameterized queries, least-privilege database accounts, and input validation.
Read postTroubleshooting CORS Errors in Production: Step-by-Step Guide
Diagnose missing CORS headers, blocked OPTIONS preflights, proxy errors, and credential mismatches without weakening API security.
Read postFix Next.js Hydration Mismatches: Causes and Safe Solutions
Troubleshoot React hydration errors in Next.js from dates, browser-only APIs, random output, incorrect markup, and third-party libraries.
Read postFix TypeScript 'any' Spreading: Validate Unknown Values Safely
Troubleshoot TypeScript spread errors with unknown values, object narrowing, safe merge patterns, and typed generics.
Read post