Database Optimization: 12 Proven Techniques

Database optimization is the work of making a database answer queries using less time, CPU, memory and disk I/O. In practice it means finding the few queries that cost the most, reading how the database executes them, and fixing them with better indexes, better SQL, better configuration or less traffic to the database in the first place.
Most applications do not need all of it. A handful of slow, frequent queries usually cause most of the pain, so the order matters: measure first, then fix the biggest offender, then measure again. The examples below use PostgreSQL and MySQL, but the ideas apply to almost every relational database.
The 12 techniques at a glance
| # | Technique | Fixes | Effort |
|---|---|---|---|
| 1 | Find the expensive queries | Optimizing the wrong thing | Low |
| 2 | Read the execution plan | Guessing at causes | Low |
| 3 | Index the columns you filter and join on | Full table scans | Low |
| 4 | Order composite index columns correctly | Indexes the planner ignores | Low |
| 5 | Keep indexed columns out of functions | Indexes the planner cannot use | Low |
| 6 | Select only the columns you need | Wasted I/O and memory | Low |
| 7 | Remove N+1 query patterns | Hundreds of tiny queries per page | Medium |
| 8 | Use keyset pagination for large tables | Slow deep pages | Medium |
| 9 | Keep statistics fresh | Bad plans for good queries | Low |
| 10 | Give the database enough memory | Constant disk reads | Low |
| 11 | Pool connections | Connection storms and exhaustion | Medium |
| 12 | Cache, replicate or partition | Load one server cannot handle | High |
1. Find the expensive queries first
The most expensive query is not always the slowest one. A report that runs once a day for 30 seconds costs far less than a lookup that runs 1,000 times an hour at 2 seconds each. Rank queries by total time (calls multiplied by average duration), not by single-run duration.
- PostgreSQL: enable the
pg_stat_statementsextension and sort bytotal_exec_time. - MySQL: turn on the slow query log with a low
long_query_time, or queryperformance_schema.events_statements_summary_by_digest.
-- PostgreSQL: top 10 queries by total time
SELECT query, calls, round(total_exec_time) AS total_ms, round(mean_exec_time) AS avg_ms
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;Start at the top of that list. Fixing one query there often does more than tuning ten from further down.
2. Read the execution plan
An execution plan shows how the database actually runs a query: which indexes it uses, which tables it scans, how it joins and sorts. EXPLAIN ANALYZE runs the query and reports real timings and row counts (PostgreSQL, and MySQL 8.0.18 or later).
EXPLAIN ANALYZE
SELECT id, email FROM users WHERE status = 'active' AND created_at > '2026-01-01';Look for three things:
- Sequential or full table scans on large tables, a sign of a missing or unusable index.
- Estimated rows far from actual rows, a sign of stale statistics (technique 9).
- Sorts or hash operations that spill to disk, a sign of too little working memory or a missing index that could return rows already sorted.
3. Index the columns you filter and join on
An index lets the database jump to matching rows instead of reading the whole table. Add indexes for the columns that appear in WHERE, JOIN and ORDER BY clauses of your expensive queries, and on foreign keys that are joined often.
Indexes are not free. Each one takes storage and slows down INSERT, UPDATE and DELETE, because the index has to be updated too. Remove indexes the database never uses: PostgreSQL's pg_stat_user_indexes shows indexes with zero scans.
4. Order composite index columns correctly
A composite index on (status, created_at) helps queries that filter on status, or on status and created_at together. It does not help a query that filters only on created_at, because indexes are used from the leftmost column.
As a rule of thumb, put columns compared with equality (=) first and columns used for ranges (>, <, BETWEEN) or sorting last.
-- Supports: WHERE status = 'active' AND created_at > '2026-01-01' ORDER BY created_at
CREATE INDEX idx_users_status_created ON users (status, created_at);If a query only needs columns that are all in the index, the database can answer from the index alone (a covering or index-only scan), which is faster still.
5. Keep indexed columns out of functions
Wrapping an indexed column in a function usually stops the database from using a normal index on it.
-- Slow: the index on created_at cannot be used
SELECT * FROM orders WHERE DATE(created_at) = '2026-11-04';
-- Fast: same result, index-friendly range
SELECT * FROM orders
WHERE created_at >= '2026-11-04' AND created_at < '2026-11-05';The same applies to LOWER(email) = ..., arithmetic on columns, and leading wildcards such as LIKE '%term'. Rewrite the condition, or create an expression index that matches it exactly.
6. Select only the columns you need
SELECT * reads and sends every column, including large text and JSON fields you may never use. Naming the columns cuts I/O and memory, and makes covering indexes possible.
-- Instead of SELECT * FROM users WHERE status = 'active';
SELECT id, name FROM users WHERE status = 'active';7. Remove N+1 query patterns
An N+1 pattern is one query to fetch a list, then one more query per item in that list. Loading 50 orders and then each order's customer separately means 51 round trips. ORMs make this easy to do by accident.
Fetch related data in one go instead, with a join or a single WHERE id IN (...) query. Most ORMs have an eager-loading option for exactly this (includes in Rails, select_related and prefetch_related in Django, with in Laravel).
8. Use keyset pagination for large tables
LIMIT 20 OFFSET 100000 makes the database read and discard 100,000 rows before returning 20, so deep pages get slower and slower. Keyset (or cursor) pagination remembers where the last page ended and starts from there using an index.
-- Next page after the last id the client saw
SELECT id, title FROM posts
WHERE id > 100020
ORDER BY id
LIMIT 20;9. Keep statistics fresh
The query planner chooses plans based on statistics about how data is distributed. If those statistics are out of date, for example after a large import, it can choose a terrible plan for a perfectly good query.
Autovacuum (PostgreSQL) and automatic statistics updates (MySQL InnoDB) handle this most of the time. After bulk loads or big deletes, run ANALYZE table_name; (PostgreSQL) or ANALYZE TABLE table_name; (MySQL) yourself. In PostgreSQL, also make sure autovacuum keeps up, because dead rows left behind by updates and deletes slow down scans.
10. Give the database enough memory
Reading from memory is orders of magnitude faster than reading from disk, so the database's cache should hold your frequently used data and indexes.
| Setting | Database | Common starting point |
|---|---|---|
shared_buffers |
PostgreSQL | About 25% of RAM on a dedicated server |
innodb_buffer_pool_size |
MySQL | 50 to 75% of RAM on a dedicated server |
work_mem |
PostgreSQL | Raise carefully if sorts spill to disk; it applies per operation |
Treat these as starting points, then check the cache hit ratio and disk reads under real load before changing them further.
11. Pool connections
Opening a database connection is expensive, and each open connection uses memory on the server. Without pooling, traffic spikes create a flood of new connections that can exhaust the server's connection limit and make every query wait.
Use a pool in your application or a pooler in front of the database, such as PgBouncer for PostgreSQL or ProxySQL for MySQL. Size the pool to what the database can actually run in parallel, which is often far fewer connections than you would expect, and set sensible idle and wait timeouts.
12. Cache, replicate or partition when one server is not enough
Once queries and indexes are in good shape, the next gains come from sending less work to the primary database:
- Cache results that are read often and change rarely, in the application or a store such as Redis. Decide up front how stale the data is allowed to be.
- Read replicas take read-only queries off the primary. Expect a small replication delay, so send reads that must see the latest write to the primary.
- Partitioning splits a very large table, often by date, so queries and maintenance only touch the relevant part.
- Sharding spreads data across several database servers. It scales furthest but adds a lot of application complexity, so treat it as a last resort.
Common mistakes
Adding indexes without checking the plan. An index the planner does not use only slows down writes. Confirm with EXPLAIN ANALYZE before and after.
Tuning on a laptop dataset. A query that is fast on 1,000 rows can be slow on 10 million because the plan changes. Test with production-sized data.
Optimizing the slowest query instead of the costliest. Rank by total time, as in technique 1.
Upgrading hardware first. A bigger server hides a bad query for a while. A missing index often fixes it for good.
Keep watching after you optimize
Database performance drifts as data grows and new features ship, so a query that is fine today can be the bottleneck next quarter. Track query latency and slow-query counts in your database tooling, and watch what users actually experience from the outside.
Odown checks your website and API endpoints from multiple locations and alerts you when response times climb or requests start failing, which is often the first visible sign of a database problem. For what counts as fast, see what is a good API response time, and for the database side of monitoring, read our guide to database performance monitoring.
FAQ
What is database optimization? It is the process of making a database run queries faster and with fewer resources, mainly through indexing, rewriting queries, tuning configuration and reducing load with caching, pooling and replicas.
What is the most effective database optimization technique?
Usually indexing the columns your most expensive queries filter and join on. Find those queries first with pg_stat_statements or the MySQL slow query log, then check the plan with EXPLAIN ANALYZE.
How do I know if my database is the bottleneck? Compare application response times with database query times. If most of each request's time is spent waiting on queries, or the database shows high disk reads, lock waits or connection limits, the database is the bottleneck.
Can too many indexes hurt performance? Yes. Every index slows down writes and uses storage and memory. Remove indexes that are never used and avoid overlapping ones.
How often should a database be optimized? Continuously in small steps. Review your top queries regularly, after major releases and after big data growth, rather than in one large project.


