Database optimization is the process of improving query speed, reducing resource consumption, and increasing throughput by finding and eliminating bottlenecks in a database system. That definition matters because it names the order of the work: find first, fix second. Most slow databases are not fixed by a bigger server or a new tool. They are fixed by a handful of changes, made in a specific order: measure what is slow, read the execution plan, fix the query, add the right index, cache what stays hot, and scale only when the cheaper fixes run out. This guide follows that order, instead of handing you a flat list of tips and leaving you to guess which one applies to your problem.
The scope here is mainly relational databases — PostgreSQL, MySQL, and SQL Server — because that is where most of the questions in this area live, and where the techniques below are most directly applicable. In-memory systems, NoSQL stores, and vector databases appear where they change the answer, not as a separate guide bolted on at the end.
Database Optimization at a Glance
The techniques table
The table below is the whole guide in miniature. If you only remember one thing from this article, make it this: every technique fixes a different problem, and applying the wrong one wastes time at best and makes things worse at worst.
| Technique | What it fixes | When to use it | When NOT to use it |
|---|---|---|---|
| Query rewriting | Queries that read more data than they need | SELECT * on wide tables, functions on indexed columns, unfiltered joins | When the plan shows the query is already selective and indexed |
| Indexing | Full-table scans on filtered columns | Columns that appear in WHERE, JOIN, and ORDER BY clauses | Write-heavy tables, low-cardinality columns, indexes no query uses |
| Statistics refresh | The optimizer choosing bad plans | After bulk loads, deletes, or schema changes | As a substitute for a missing index or a bad query |
| Schema design and normalization | Redundancy and update anomalies | Tables that store the same fact in several places | When read performance is the problem and joins are already cheap |
| Denormalization | Expensive joins on read-heavy data | Dashboards and reports that join the same tables every time | Before the plan proves joins are the bottleneck |
| Caching | Repeated reads of the same data | Hot, slowly changing data such as catalogs and sessions | Data that changes constantly, or a query that is slow for another reason |
| Connection pooling | Connection exhaustion under load | Many application instances sharing one database | A single-instance application with a handful of connections |
| Partitioning | Huge tables where queries filter on one key | Time-series and log tables queried by date range | Tables where queries rarely filter on the partition key |
| Read replicas | Read load overwhelming the primary | Read-heavy workloads with tolerance for slight staleness | Write-heavy workloads, or reads that must be perfectly current |
| Sharding | A single server that cannot grow further | Very large datasets with a clean shard key | Before replicas and partitioning have been tried |
| Hardware and configuration tuning | Genuine resource limits | A tuned system still saturating CPU, memory, or disk | As the first response to a slow query |
| Monitoring | Problems discovered by users instead of by you | Every production database, from day one | Never — this one has no “do not use” case |
What Is Database Optimization?
Definition, expanded
Database optimization covers performance, efficiency, and management — not just raw speed. A database can return results quickly and still be badly optimized: it might burn far more CPU and disk than necessary, cost far more to run than it should, or fall over the moment traffic spikes. Optimization means the database does the least work needed to answer each question, uses resources sensibly, and keeps behaving well as data and traffic grow.
Optimization vs tuning
The two words are often used interchangeably, and the distinction is worth keeping straight because it tells you where to look. Optimization is the broad work: queries, schema, indexes, and caching. Tuning is the narrower work: adjusting settings on a database that already exists — buffer pool size, connection limits, memory allocation. If your queries are bad, no amount of tuning will save you. If your queries are good and the server is still saturated, tuning is exactly the right next step. Confusing the two is how teams end up raising memory limits on a database whose real problem is a missing index.
Why it matters
Slow databases hurt in four places at once. Users wait, and waiting users leave or file support tickets. The application itself slows down, because almost every page, report, and API response waits on the database at some point. Scaling gets harder, because an unoptimized database needs more hardware to serve the same traffic. And cost rises, because cloud databases charge for the resources they consume — a query that scans an entire table on every request is not just slow, it is expensive, every single time it runs. Optimization is, among other things, a cost discipline.
First, Measure: The Four Golden Signals

Latency, traffic, errors, saturation
Before changing anything, measure four things. Together they are often called the four golden signals, and each one points at a different kind of problem.
Latency is the time between sending a query and getting its result. High latency on user-facing queries is the signal users feel first. Traffic is the volume of requests the database receives, usually measured in queries or transactions per second. A database that coped fine at one traffic level can degrade sharply at a higher one, and the degradation often looks like a query problem when it is really a capacity problem. Errors are the requests that fail outright — invalid queries, deadlocks, timeouts. A rising error rate usually means concurrency trouble or application bugs, not slow queries. Saturation is how close the database is to its resource limits: CPU, memory, disk I/O, and network. SolarWinds’ guide cites roughly 50–70% CPU utilization as a healthy range, with degradation setting in above it; treat that as a rule of thumb to watch against, not a law, because the right threshold depends on your workload.
The point of measuring all four is that they stop you guessing. High latency with low saturation points at a bad query. High latency with high saturation points at a resource problem. Rising errors with rising traffic points at concurrency. Each combination suggests a different fix, and the diagnosis workflow below is built around reading them in that order.
Averages lie: p99 latency
Averages hide the queries that matter. If most queries return in milliseconds and a small fraction take seconds, the average can look perfectly healthy while a meaningful share of users waits. That is why production teams watch percentiles, especially p99 — the latency that 99% of queries beat. p99 tells you what the slowest real users experience, which is usually what support tickets and churn are about. When you benchmark a change, compare p99 before and after, not just the average. A fix that improves the average while leaving p99 unchanged has not fixed the experience that was actually broken.
The tools that measure for free
You do not need a paid platform to start measuring. Every major database ships the tools this guide relies on, and they are covered in detail in the tools section at the end: the slow-query log, PostgreSQL’s pg_stat_statements extension, MySQL’s Performance Schema, SQL Server’s Query Store, and the dashboards that come with managed cloud databases. Turn them on before you need them. A slow-query log that only starts recording after the incident is no help at all, and the most common monitoring mistake is discovering, mid-outage, that nobody ever enabled it.
The Diagnosis Workflow: Measure → Plan → Fix → Benchmark → Monitor

Step 1 — Find the slowest queries
Do not start with the query you suspect. Start with the query the data indicts. Rank queries by total time consumed — how long they take multiplied by how often they run — not by the single slowest run. A query that takes a second but runs ten thousand times a day costs far more than a query that takes ten seconds but runs once a week. pg_stat_statements, the slow-query log, and Query Store all give you this ranking. Pick the top few. That short list is your optimization backlog, and it is almost always shorter and more surprising than the list you would have guessed.
Step 2 — Read the execution plan

The execution plan is the database’s own explanation of how it will run your query, and it is the single most useful document in database optimization. In PostgreSQL you get it with EXPLAIN, and with EXPLAIN ANALYZE you get the plan plus the actual timings from running it. PostgreSQL’s official Using EXPLAIN guide is the best place to learn plan reading in depth, and it is worth working through its examples once, because the skill transfers to every database.
Two lines in a plan tell you most of what you need. A Seq Scan means the database is reading every row in the table. That is sometimes fine — for a small table, or a query that genuinely needs most rows — but on a large table with a selective filter, it is the first thing to fix. An Index Scan means the database is using an index to jump straight to the rows it needs. The plan also shows cost estimates and, with ANALYZE, actual times. One warning about those cost numbers: they are planner units, not milliseconds. They are useful for comparing plans against each other, not for predicting wall-clock time. When the estimated row count and the actual row count disagree wildly, that mismatch itself is a clue — it usually means the optimizer is working from stale statistics, which the query section below addresses.
Step 3 — Match the symptom to the fix
Once you have a plan, match what you see to the fix it implies. This table is the shortcut version of the whole guide:
| Symptom | What to check | Likely fix |
|---|---|---|
| Slow queries | Execution plans and indexes | Rewrite the query or add an index |
| High CPU | The most expensive queries by total time | Query tuning first, more resources second |
| Same data read again and again | Cache hit ratio and access patterns | Caching |
| Slow queries on one huge table | Scans and statistics | Partitioning, if queries filter on the partition key |
| Requests waiting to connect | Pool usage and long transactions | Pool tuning and shorter transactions |
| Slow dashboards | Repeated heavy aggregations | Materialized views or summary tables |
| Cloud bill keeps rising | CPU, storage, and I/O by query | Query fixes, then right-size the instance |
One symptom can have several causes. High CPU might come from one bad query, or from a cache that stopped working, or from a traffic spike. When in doubt, follow the same loop every time rather than jumping to the fix that feels most familiar.
Step 4 — Change ONE thing, benchmark, monitor
Change one thing, benchmark it, and monitor the result before changing anything else. This discipline sounds slow and feels slow, and it is the reason the loop works. If you add an index, rewrite a query, and raise memory on the same afternoon, and performance improves, you will never know which change helped — and you will keep paying for the two that did not. Benchmark with realistic data volume, not a thousand-row test table, because a change that looks great on tiny data can fail on ten million rows. Then keep monitoring after release, because many problems only appear under real traffic, and the next bottleneck is always on its way.
Query Optimization: Rewrite Before You Buy Anything
Select only the columns you need
SELECT * is the most common wasteful habit in application code. On a wide table it forces the database to read, transfer, and materialize columns nobody asked for, and it defeats covering indexes that could otherwise answer the query from the index alone. Selecting the two columns you actually need is not a micro-optimization; on a wide table it is often the difference between an index-only plan and a trip to the table for every row. When you see SELECT * in a slow query, that is the first line to question.
Sargable WHERE clauses
A WHERE clause is sargable when the database can use an index to satisfy it. The classic way to break that is to wrap an indexed column in a function. Consider a query filtering orders by date:
SELECT * FROM orders WHERE DATE(order_date) = '2024-01-01';
Because the DATE() function is applied to the column, the database must evaluate it for every row, and it cannot simply look up the date in an index. The rewrite is a plain range:
SELECT * FROM orders WHERE order_date >= '2024-01-01' AND order_date < '2024-01-02';
The range version can use an index on order_date directly, and it says exactly the same thing. The same principle applies to YEAR(order_date), UPPER(name), and any other function wrapped around a filtered column: move the transformation to the other side of the comparison, or store a computed column, and let the index do its job.
Filter early in JOINs, and EXISTS over IN for subqueries
Joins are expensive in proportion to the rows they touch, so filter before you join, not after. A WHERE clause that restricts orders to a date range before joining them to customers means the join processes a fraction of the rows it otherwise would. The same early-filtering logic applies inside subqueries. For existence checks, EXISTS usually beats IN, because EXISTS stops at the first matching row while IN must gather all matches:
SELECT * FROM clients c WHERE EXISTS (SELECT 1 FROM purchases p WHERE p.client_id = c.id);
Compared with the IN version, which collects every matching client_id before filtering, the EXISTS version does less work for the same answer — and the plan will show it.
The query optimizer and stale statistics
The query optimizer is the component that chooses between possible plans — which index to use, which join order, whether to scan or seek. It makes those choices from statistics: estimates of how many rows a table holds, how values are distributed, and how selective each column is. When statistics go stale — after a bulk load, a large delete, or a schema change — the optimizer starts guessing badly, and good queries get bad plans for no visible reason. The fix is unglamorous: refresh statistics. In PostgreSQL that is ANALYZE, and the autovacuum process handles it routinely; in MySQL it is ANALYZE TABLE. If a query suddenly slows down after a data load, and nothing about the query changed, stale statistics are the first suspect, not the query itself.
N+1 and ORM pitfalls
The N+1 problem is the practitioner bug that forum threads complain about most, and it rarely shows up in a single query’s plan. It happens when application code fetches a list of rows, then runs one extra query per row inside a loop — one query for the list, plus N queries for the details. Each individual query is fast. Together they are a flood. You spot it in the slow-query log as the same query shape repeated hundreds of times, or in the application as a page that makes hundreds of database round trips. The fix is at the application layer: fetch the related data in one joined or batched query, or use the ORM’s eager-loading option. No index fixes N+1, because the problem was never a slow query — it was too many queries.
Indexing: The Biggest Single Win, and the Easiest to Overdo

How an index works
An index is like the index at the back of a book: a sorted list of keys, each pointing at where the data actually lives, so the database can jump to the right rows instead of reading the whole book. An index entry has a search key and a pointer to the row. Keys are usually kept in sorted order, which is what makes range queries fast: once the database finds the start of the range, the rows it needs are adjacent. That single idea explains both the power of indexes and their cost. Every index is a second structure the database must maintain, and every write to the table must update every index on it.
Index-types comparison table
Not all indexes are the same tool, and choosing the wrong type is a common source of disappointment:
| Index type | Best for | When NOT to use it |
|---|---|---|
| B-tree | Equality and range queries; the default in most relational databases | Rarely wrong, but not the best for full-text or array data |
| Hash | Exact-match equality lookups only | Range queries — hash indexes have no key ordering, so a range scan must visit every row |
| GIN | Full-text search and array or JSONB containment | Simple equality or range queries, where a B-tree is cheaper |
| BRIN | Very large, naturally ordered tables such as time-series data | Small tables, or tables where values are not physically ordered |
| Composite (multi-column) | Queries that filter on several columns together | When queries filter on only the second column — column order matters |
| Partial | Queries that always filter on the same condition, such as active rows only | When the condition varies — a partial index only helps queries that match its predicate |
Hash indexes deserve a specific note because their availability varies. They exist in PostgreSQL, Oracle, and MySQL’s InnoDB engine, and they are useful only for equality matches. SQL Server handles hashing differently: it does not offer a manually created hash index, and instead may choose a hash join during query processing when the tables are large and the keys are unsorted or unindexed. Porting index advice between engines without checking this kind of difference is a reliable way to write a guide that is wrong on one database out of three.
Composite indexes and column order
A composite index on (category, price) helps queries that filter on category, or on category and price together. It does not help queries that filter on price alone, because the index is sorted by category first — finding all rows with a given price would mean scanning every category group. The rule is simple: put the most selective, most commonly filtered column first, and order the rest by how queries actually filter, not by how columns happen to appear in the table definition. If a query filters on two columns but your index covers only one, the database still scans far more rows than it should, and the fix is usually a composite index, not a faster server.
Over-indexing and unused indexes
Indexes speed up reads and slow down writes, and they cost disk space. A table with indexes on every column is a table that pays for every index on every insert, update, and delete, while most of those indexes are never used by any query. The honest maintenance habit is to check which indexes are actually used — PostgreSQL and MySQL both expose index usage statistics — and drop the ones that are not. Related to this is overhead in the broader sense: dead rows left behind by updates and deletes, fragmentation, and bloat. In PostgreSQL, vacuuming clears out dead rows so the table and its indexes stay compact; in MySQL, optimizing a table serves a similar purpose. Overhead is not glamorous, but a bloated table makes every scan and every index lookup do more work than it should.
Worked before/after: a plan reading
Here is how a plan reading works in practice, using an illustrative example rather than a benchmark claim. Suppose a query looks up a customer’s orders and the plan shows a Seq Scan on a large orders table. That line means the database is reading every row in the table to find the handful that match. Adding an index on the customer column, and reading the plan again, should show the scan replaced by an Index Scan using that index, with the filter applied as an index condition rather than a filter over all rows. The cost figures in the two plans will fall, because the planner now expects to visit far fewer pages. What matters is not the absolute cost number — remember, planner units are not milliseconds — but the change in access method, and the change in estimated rows visited. If the plan does not change after adding an index, the index is not the fix: the query, the statistics, or the column order is the problem, and the plan is telling you so.
Schema Design: Normalization, Denormalization, and When Each Wins

Normalization in brief
Normalization is the process of restructuring a database to remove redundancy and protect data integrity, by splitting large tables into smaller, related ones. In its first normal form, every column holds a single value and every record is unique — a table that stores “Order1, Order2” in one cell is not in first normal form, and splitting it so each order gets its own row is the fix. Second normal form removes partial dependencies, so facts about a product live in a products table rather than being repeated on every order row. Third normal form removes transitive dependencies: a column should depend on the key, the whole key, and nothing but the key. If a product’s price sits on an order-details row, changing the price means updating every order that ever mentioned the product; in third normal form it sits in the products table, and it changes in exactly one place.
The optimization payoff is real: smaller tables, less storage, faster writes, and fewer chances for inconsistent data. Beyond third normal form there are further forms — Boyce-Codd, fourth, and fifth — but for most applications, third normal form is where the practical benefit plateaus, and further decomposition starts costing more in join complexity than it saves in redundancy.
Denormalization, only when the plan proves joins are the problem
Denormalization is the deliberate reversal of that process: duplicating data to avoid joins on read-heavy paths. It is a legitimate optimization, and it is one of the most misapplied ones. The rule is strict: denormalize only when an execution plan shows joins are the actual bottleneck, and only for the data involved. A dashboard that joins the same five tables on every load is a candidate. A table you denormalized because you assumed joins would be slow, before measuring anything, is a maintenance liability — every copy of a duplicated fact must now be kept in sync, and the first time one copy drifts, you have a data integrity bug that no index will fix.
The safer middle ground for repeated aggregations is a materialized view or a summary table: precompute the expensive aggregation on a schedule, and let dashboards read the summary instead of recomputing it on every request. Refresh during low-traffic periods, and the dashboard gets fast reads without the write-amplification of full denormalization.
Partitioning large tables
Partitioning splits a large table into smaller physical pieces, usually by a key such as date, so queries that filter on that key only touch the relevant pieces. A time-series table queried almost always by month is an ideal candidate: a query for last month’s data reads one partition instead of the whole table. But partitioning is not a general speedup. If queries rarely filter on the partition key, they still touch every partition, and you have added complexity for no gain. Partition when the filter pattern matches the partition key, and verify in the plan that the database is actually pruning partitions it does not need.
Caching: Avoid Running the Query at All

Caching-strategies comparison table
Caching stores frequently accessed data temporarily so the database does not have to redo the same work for every request. The three standard strategies differ in who loads the cache and who writes to it:
| Event | Cache-aside | Read-through | Write-through |
|---|---|---|---|
| Cache miss | Application loads data into cache from the database | Cache loads data from the database | Cache loads data from the database |
| Write behavior | Application writes to the database | Application writes to the database | Cache writes to the database |
| Best applications | User sessions, product catalogs | Search engines, pricing data | Financial transactions, online orders |
Cache-aside is the most common and the most flexible: the application checks the cache first, falls back to the database on a miss, and populates the cache itself. Read-through moves that logic into the cache layer, which suits workloads where freshness matters and the application should not know about caching at all. Write-through keeps the cache current on every write, at the cost of slower writes, which suits data where a stale read is unacceptable. Pairing write-through with read-through is a common way to keep a cache both fresh and fast.
What to cache, and invalidation
Cache data that is hot, read-heavy, and slowly changing: product catalogs, user sessions, pricing pages, reference data. Do not cache data that changes constantly, because the cache will spend more time invalidating than serving. And treat invalidation as the hard part of caching, not an afterthought. A stale cache is worse than a slow query, because a slow query eventually returns the right answer while a stale cache confidently returns the wrong one. Every cached item needs an invalidation rule — a time-to-live, an explicit invalidation on write, or both — decided before the cache goes live, not discovered after users start seeing yesterday’s prices.
In-memory options
Redis and Memcached are the standard in-memory caching layers, and they are best understood as a cache in front of a database, not as a replacement for one. They hold hot data in memory for fast access, which removes disk reads from the hottest paths, but the database of record still owns durability and consistency. One specific warning for MySQL users: the built-in query cache was deprecated in MySQL 5.7 and removed in MySQL 8.0, so any guide that still recommends it is out of date. Use an external cache layer instead, and size it by the working set you actually measured, not by a guess.
Connections, Locks, and Concurrency

Connection pooling first
When an application creates a new database connection for every request, it pays the full cost of establishing that connection every time, and under load it can exhaust the database’s connection limit — at which point new requests queue or fail while the database itself sits idle waiting for connections to free up. Connection pooling reuses a set of open connections across requests, and for high-concurrency systems it is often the first fix worth making, ahead of query work, because pool exhaustion looks exactly like a slow database while being a completely different problem. PgBouncer for PostgreSQL and HikariCP for Java applications are the standard tools. Two pooling modes matter: transaction-mode pooling returns a connection to the pool after each transaction, which maximizes reuse, while session pooling holds a connection for a whole session, which is necessary for multi-step operations that keep state across queries. Pool sizing should be based on measured throughput and latency, starting small and adjusting — a pool sized by guesswork is just a new bottleneck in a different place.
Lock contention
When concurrent transactions compete for the same rows, they wait, and waiting transactions hold their own locks longer, which makes other transactions wait in turn. The fixes are mostly about keeping transactions short and narrow: do the minimum work inside the transaction, commit promptly, and do not hold a transaction open across a network call or user interaction. Isolation levels are the other lever. PostgreSQL defaults to READ COMMITTED and MySQL’s InnoDB engine defaults to REPEATABLE READ, and the names do not mean identical things on the two engines — a level that prevents phantoms on one may not on the other. The practical rule is to use the loosest isolation level your application can safely live with, and to check the engine’s documentation before changing a default, because stricter levels protect data better but cause more waiting, and the trade-off is workload-specific.
Read vs write balance
Optimizing reads can hurt writes, and this trade-off is easy to miss when every metric you watch is read latency. Every index you add speeds up some reads and slows down every write to that table. Read replicas are the standard escape hatch: route read-heavy traffic to replicas and keep the primary for writes, which lets reads scale without burdening the write path. The cost is staleness — replicas lag the primary by some amount, so reads that must be perfectly current, such as a balance immediately after a payment, still belong on the primary. Read-write splitting is a design decision about which reads can tolerate that lag, not a switch you flip globally.
Resources, Configuration, and the Scaling Ladder — Scale LAST

Hardware and configuration
Genuine resource limits do exist, and when they do, the fixes are straightforward: a larger buffer pool keeps more hot data in memory and reduces disk reads; SSD or NVMe storage replaces slow disk I/O; adequate free disk space prevents the performance cliff of a nearly full volume; and a write-ahead log sized for the write workload avoids constant forced flushing during heavy writes. The discipline matters more than any single setting: tune for your actual workload, not for a blog post’s recommended values, and change one setting at a time so you know which change helped. A reporting database and a checkout database need very different settings, and a configuration copied from either will be wrong for the other.
The scaling ladder in order
Scaling is a ladder, and the rungs should be climbed in order, cheapest and simplest first. Right-size the instance: after query fixes, the instance you actually need is often smaller than the one you were running, not larger. Add read replicas for read load. Partition the largest tables where the filter pattern supports it. Shard — split data across several servers — only when the previous rungs are exhausted. Sharding adds real complexity: cross-shard queries, rebalancing, and operational overhead that does not go away. And it carries a specific warning: choose the shard key carefully, because a key that concentrates traffic on one shard — a celebrity account, a single popular product — creates a hotspot that defeats the entire purpose of splitting the data.
Cost optimization
Treat the cloud bill as a diagnostic signal, not just an expense. A bill that keeps rising while traffic is flat usually means queries are doing more work than they need to — more CPU, more I/O, more storage scanned. Fix the queries first, then right-size the instance to the workload that remains. Right-sizing before fixing queries just buys a larger server to run the same wasteful work on, and the bill will climb again. The cheapest infrastructure change is usually a query change.
Hybrid and cloud environments in brief
Managed cloud databases handle patching, backups, and much of the operational burden, and they come with useful built-in dashboards for metrics and slow-query views. What they do not do is fix slow SQL. You still own the schema, the queries, and the indexes, and a managed service will happily run a bad query on expensive hardware for as long as you let it. In hybrid environments, where some data lives on premises and some in the cloud, the same rule applies twice: monitor both sides, watch data-transfer costs between them, and do not assume the cloud side is somehow self-optimizing.
By Database: PostgreSQL vs MySQL vs SQL Server

One comparison table
The techniques in this guide apply across engines, but the tools and defaults differ, and the table below collects the differences that most often trip people up when they move between databases:
| Area | PostgreSQL | MySQL (InnoDB) | SQL Server |
|---|---|---|---|
| Plan tool | EXPLAIN, EXPLAIN ANALYZE | EXPLAIN, EXPLAIN ANALYZE | Execution plan viewer, Query Store |
| Statistics refresh | ANALYZE; autovacuum handles it routinely | ANALYZE TABLE | Automatic statistics updates |
| Dead-row cleanup | VACUUM / autovacuum | OPTIMIZE TABLE | Automatic, with index maintenance |
| Query cache | Not applicable (use an external cache) | Removed in MySQL 8.0 — do not use | Result caching via in-memory features |
| Default isolation level | READ COMMITTED | REPEATABLE READ | READ COMMITTED |
| Hash handling | Hash indexes available for equality lookups | Hash indexes available with InnoDB | No manual hash index; hash joins chosen by the optimizer |
| Pooling tools | PgBouncer | ProxySQL, built-in pooling in connectors | Built-in connection pooling in drivers |
| Slow-query tracking | pg_stat_statements, slow-query log | Slow query log, Performance Schema | Query Store, extended events |
MySQL large-database notes and PostgreSQL notes
For large MySQL databases, the highest-value habits are the ones this guide already covers, applied with MySQL’s specifics in mind: keep InnoDB buffer pool sized for the working set, watch for the query-cache trap above, use the slow query log and Performance Schema to rank queries by total time, and remember that REPEATABLE READ’s gap locking can surprise applications ported from PostgreSQL — switching to READ COMMITTED is common once a team has checked its code does not rely on repeatable reads. For PostgreSQL, the highest-value habits are keeping autovacuum healthy so dead rows do not bloat tables, refreshing statistics after bulk changes, and reading EXPLAIN ANALYZE output as a matter of routine rather than only during incidents. Neither database rewards a different optimization philosophy; they reward the same workflow, executed with the right tool names.
By Workload: OLTP, Analytics, Cloud, and AI/RAG
Transactional (OLTP)
Transactional systems handle many small reads and writes — orders, sign-ins, payments — and speed and consistency come first. The playbook is tight indexes, short transactions, and a good connection pool, with caution about extra indexes, because every additional index slows every write on a system that writes constantly. On an OLTP system, the most expensive mistake is usually not a missing index but an open transaction or an unpooled connection storm during a traffic spike.
Analytics (OLAP)
Analytics systems scan huge amounts of data for reports, and the playbook inverts: partitioning, columnar storage, and pre-built summaries help most, while row-level indexes matter far less. On platforms such as Snowflake and BigQuery, tuning is mostly about how much data a query scans, not about row-by-row index design — a query that scans a whole year’s data when it needs a month is the analytics equivalent of a full-table scan, and the fix is the same in spirit: read less data.
AI apps, RAG, and vector search
An AI application that retrieves related text before answering — retrieval-augmented generation, or RAG — is only as fast as its retrieval step. A slow lookup makes the whole AI answer slow, whatever the model does afterwards. The same basics apply: the right indexes, narrow queries, cached repeat lookups, and latency monitoring. Vector search adds a new index trade-off: in pgvector, for example, HNSW indexes generally give better speed and recall but use more memory and build more slowly than IVFFlat, so the choice depends on your data and your tolerance for build time. Test on your own data rather than trusting a benchmark, and for a deeper treatment of how vector databases are organized, see the guide to vector databases — the retrieval layer and the database layer are the same performance problem viewed from two sides.
WordPress databases in brief
WordPress sites are a practical special case worth one short section, because their database problems are usually not exotic. Overhead accumulates from post revisions, expired transients, spam comments, and orphaned metadata, and routine cleanup of those tables is the WordPress equivalent of vacuuming. A caching plugin helps with repeated reads, but it does not fix a bad query — a slow query behind a cache is still a slow query the first time it runs, and it still runs on every cache miss. For a WordPress database, the workflow in this guide applies unchanged: find the slow queries in the log, read their plans, fix the queries, and only then reach for a bigger server or another plugin.
Common Mistakes Checklist
- Guessing the bottleneck — adding a cache to a problem caused by a missing index.
- Too many indexes — reads get faster and writes get slower, while storage grows.
- Testing on tiny data — a change that looks great on a thousand rows can fail on ten million.
- Changing five things at once — you will never know which one helped.
- Ignoring old statistics — stale statistics lead the optimizer to bad plans.
- Leaving transactions open — they hold locks and block everyone else.
- Denormalizing too early — you get copies to maintain and no proof they were needed.
- Not watching after release — many problems only show up under real traffic.
- SELECT * everywhere — reading columns nobody asked for, on every query.
- N+1 queries from an ORM — hundreds of fast queries that add up to a slow page.
Tools (Built-In First)
Tools table
You do not need paid third-party platforms on day one. The best database optimization tools come built into the engine, and the table below is the shortlist worth learning first:
| Tool | What it helps with |
|---|---|
| EXPLAIN / EXPLAIN ANALYZE | Shows how a query runs, with estimates and actual timings |
| pg_stat_statements | Ranks PostgreSQL queries by total time |
| MySQL Performance Schema and slow query log | Finds slow MySQL queries and where time goes |
| SQL Server Query Store | Tracks query plans and performance over time |
| Cloud dashboards (CloudWatch, Query Insights) | Metrics and slow-query views for hosted databases |
| PgBouncer, HikariCP | Connection pooling |
| Redis, Memcached | In-memory caching to cut repeat reads |
| pgbench, sysbench | Load testing before and after a change |
Load testing deserves a sentence of its own: pgbench and sysbench let you measure a change before it reaches production, under a workload you control. Benchmarking on a production database during peak traffic is how an optimization attempt becomes an incident.
When to call a specialist
Most issues in this guide are handleable by the team that owns the application. Bringing in dedicated database optimization services or a database administrator makes sense when queries stay slow after the basics have been tried, when cloud costs keep climbing and nobody can say why, when a large migration is planned, or when traffic is growing faster than the current setup can handle. Before hiring anyone, gather the slow-query log, a few execution plans, and the monitoring charts — that gives an expert something concrete to work from, and it saves you money, because the first thing any good specialist will ask for is exactly that evidence.
Frequently Asked Questions
What is database optimization?
Database optimization is the process of improving query speed, reducing resource consumption, and increasing throughput by finding and eliminating bottlenecks in a database system. In practice it means measuring what is slow, reading execution plans, rewriting queries, adding the right indexes, caching hot data, and scaling only when the cheaper fixes run out.
What is the difference between database optimization and database tuning?
Optimization is the broad work: queries, schema, indexes, and caching. Tuning is the narrower work of adjusting settings on an existing database, such as buffer pool size or connection limits. Tuning helps a well-written system run better; it does not fix bad queries.
What should I fix first in a slow database?
Start with the slowest queries that run most often, ranked by total time. Check their execution plans, then look at indexes. That sequence beats any server change, because it targets the work that actually costs the most.
Do more indexes always make a database faster?
No. Indexes speed up reads but slow down writes and use disk space. Keep only the indexes your queries actually use, and check usage statistics before adding more.
Is caching better than indexing?
They solve different problems. Indexes make a query itself faster. Caching avoids running the query at all. Fix the query first, then cache what is still hot — caching a slow query just hides it until the cache misses.
When should I denormalize?
Only when an execution plan shows joins are the problem, and only for the data involved. Otherwise stay normalized, because duplicated data must be kept in sync and the first drift becomes an integrity bug.
How do I optimize a database in MySQL or PostgreSQL?
Follow the same workflow in both: rank slow queries by total time, read their plans, rewrite the queries, add indexes that match the filters, refresh statistics, and cache hot data. The by-database table above gives the tool names and defaults that differ between the two engines.
How do I optimize a WordPress database?
Clean up overhead from revisions, expired transients, and spam, find the slow queries in the log, and fix them as this guide describes. A caching plugin helps with repeated reads but does not fix a slow query behind the cache.
When should I scale instead of optimizing?
Scale last, after the cheaper fixes run out. If queries are still slow after rewriting, indexing, statistics, caching, and pooling, and the system is genuinely saturating CPU, memory, or disk, then right-sizing, replicas, partitioning, or sharding are the right next steps — in that order.
Bottom Line
Database optimization is a habit, not a project, and the habit is a short loop repeated until it becomes boring: measure what is slow, read the plan, fix the slowest query, change one thing, benchmark the result, and keep monitoring after release. The biggest wins almost always come from the basics — better SQL, the right indexes, a clear reading of an execution plan — before caching, partitioning, or scaling are ever touched, and the teams whose databases stay fast as they grow are not the teams with the most exotic tooling. They are the teams that never stopped running the loop, because the next bottleneck is always on its way, and the cheapest time to catch it is the moment it appears, not the morning users start complaining about it.
