Databases & Storage
Database Query Optimization: Indexes, EXPLAIN and Practical Fixes
By NileVPS Team · Published · 4 min read
اقرأ المقال بالعربيWhen a website or API slows down, the database is often the first place to look. A single query that scans millions of rows can tie up CPU and disk for everyone else, and adding more server resources only hides the problem for a while. The good news is that most slow queries can be fixed with a handful of techniques: finding the right query, reading its execution plan and adding or adjusting an index. This guide walks through that process for PostgreSQL and MySQL/MariaDB.
Step 1: find the slow queries
Do not guess. Measure which queries take the most total time.
PostgreSQL
Enable the pg_stat_statements extension. Add it to shared_preload_libraries in postgresql.conf, restart PostgreSQL, then run:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT query, calls, round(total_exec_time) AS total_ms, round(mean_exec_time, 2) AS mean_ms
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;You can also log every query slower than a threshold with log_min_duration_statement = 500 (milliseconds).
MySQL and MariaDB
Turn on the slow query log:
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 0.5;Then summarize it with mysqldumpslow -s t /var/log/mysql/mysql-slow.log (the path depends on your configuration; check SHOW VARIABLES LIKE 'slow_query_log_file';).
Focus on total time, not only the slowest single query. A 20 ms query called 50,000 times an hour often matters more than a 3-second report run once a day.
Step 2: read the execution plan
EXPLAIN shows how the database plans to run a query. EXPLAIN ANALYZE actually runs it and reports real timings, so use it carefully on statements that modify data (wrap them in a transaction and roll back).
EXPLAIN ANALYZE
SELECT id, total FROM orders
WHERE customer_id = 4821 AND status = 'paid'
ORDER BY created_at DESC
LIMIT 20;What to look for:
| Plan sign | What it usually means |
|---|---|
Seq Scan (PostgreSQL) or type: ALL (MySQL) on a big table | No usable index; every row is read |
| Estimated rows far from actual rows | Outdated statistics; run ANALYZE |
Sort with high cost or disk usage | An index could provide the order directly |
Nested Loop over many rows | Missing index on the join column |
Using filesort / Using temporary (MySQL) | Sorting or grouping without a supporting index |
Step 3: index wisely
An index is a sorted structure (usually a B-tree) that lets the database find rows without scanning the whole table. For the query above, a composite index fits well:
CREATE INDEX CONCURRENTLY idx_orders_customer_status_created
ON orders (customer_id, status, created_at DESC);CONCURRENTLY is PostgreSQL syntax that avoids blocking writes during creation. In MySQL 8 and recent MariaDB, InnoDB builds most secondary indexes online by default.
Rules for composite indexes
- Put columns used with equality (
=) first, then range or sort columns. - An index on
(a, b, c)helps queries filtering ona, oraandb, but usually not queries filtering only onb. - A covering index includes every column the query needs, so the table itself is not read. PostgreSQL supports
INCLUDE (col)for this.
Indexes are not free
Every index slows down inserts and updates and uses disk and memory. Remove indexes that are never used. In PostgreSQL, check pg_stat_user_indexes for indexes with idx_scan = 0 after a representative period.
Step 4: rewrite problem queries
Some patterns prevent index use or waste work:
- Functions on indexed columns:
WHERE DATE(created_at) = '2026-11-22'cannot use a plain index oncreated_at. Use a range instead:WHERE created_at >= '2026-11-22' AND created_at < '2026-11-23'. - Leading wildcards:
LIKE '%term'cannot use a B-tree index. Consider full-text search for this case. - SELECT \*: fetch only the columns you need, especially with wide tables.
- N+1 queries: an ORM loop that runs one query per row. Use joins or eager loading.
- Large OFFSET pagination:
OFFSET 100000still reads and discards those rows. Use keyset pagination (WHERE id < last_seen_id ORDER BY id DESC LIMIT 20).
Step 5: keep statistics and the server healthy
- Run
ANALYZE(PostgreSQL) orANALYZE TABLE(MySQL) after big data changes so the planner has accurate estimates. Autovacuum normally handles this in PostgreSQL; make sure it is not disabled. - Give the database enough memory:
shared_buffersandeffective_cache_sizein PostgreSQL,innodb_buffer_pool_sizein MySQL. If the working set does not fit in RAM, every cache miss becomes a disk read. - Use a connection pooler such as PgBouncer when the app opens many short connections.
If you have tuned queries and indexes and the database still needs more memory or faster storage, moving to a larger plan is straightforward; see pricing. For workloads that outgrow a single server, read about distributed databases.
Optimization checklist
- Identify top queries by total time.
- Run
EXPLAIN ANALYZEon each. - Add or adjust indexes based on filters, joins and sort order.
- Rewrite queries that block index use.
- Verify the improvement with the same measurement you started with.
- Drop unused indexes and repeat periodically.
FAQ
Should I add an index on every column?
No. Each index costs write performance, disk space and memory. Add indexes that match real query patterns found in your slow query data, and remove those that stay unused.
What is the difference between EXPLAIN and EXPLAIN ANALYZE?
EXPLAIN shows the planned strategy and estimated costs without running the query. EXPLAIN ANALYZE executes the query and shows actual row counts and timings, which reveals where estimates are wrong.
Will a bigger VPS fix slow queries?
More RAM can help if your data does not fit in memory, but it does not fix a missing index or a full table scan. Optimize queries first, then add resources if measurements still show a hardware limit.