# SQL Query Performance: EXPLAIN, Indexes, and Verification

> Read EXPLAIN and EXPLAIN ANALYZE, order composite indexes, fix N+1 queries, pagination, joins, and plan caching, and verify query speed with pass criteria.

**Quick answer:** SQL query performance is decided by the execution plan, not by the query text alone. Read EXPLAIN for estimated rows and EXPLAIN ANALYZE for actual rows, loops, time, and buffers; index the columns your predicates and sort orders really use; keep predicates sargable; and verify latency, write cost, and lock waits on production-scale data before calling a query fixed.

## Key takeaways

- EXPLAIN shows estimates and EXPLAIN ANALYZE shows actual rows, loops, time, and buffers; compare the two before changing any SQL.
- A sequential scan is often the correct plan; an index pays off only when it removes enough work to outweigh random reads and write amplification.
- Composite index order follows equality predicates, then ranges, then sort columns, and the leftmost prefix decides which queries can use it.
- Covering indexes and keyset pagination remove whole categories of work, while SELECT * and function-wrapped columns silently give them back.
- Verify with warm-cache plans, write throughput, and lock waits at realistic data volume; a fast query on a cold empty database proves nothing.

---

SQL performance is not a property of the query text. It is the result of a plan chosen from statistics, the indexes available to that plan, the distribution of the data, and the state of caches and locks at execution time. Two databases running the same statement can differ by orders of magnitude because one reads twenty rows and the other reads twenty million. The practical skill is to read the plan, form one hypothesis, change one thing, and measure again.

This guide covers how PostgreSQL and MySQL report plans, how index order and coverage change what the executor can do, why N+1 queries and deep offsets are expensive even with good indexes, and how plan caching and long transactions distort results. It ends with a verification checklist and pass criteria that separate a genuine improvement from a benchmark artifact.

## What EXPLAIN and EXPLAIN ANALYZE actually measure

Every plan starts as an estimate. `EXPLAIN` in PostgreSQL prints the plan tree with a startup cost, a total cost, an estimated row count, and an average row width for each node. The cost unit is arbitrary and comparable only within one server and one statistics snapshot; it is not milliseconds. MySQL's `EXPLAIN` prints one row per table access with columns such as `type`, `possible_keys`, `key`, `rows`, `filtered`, and `Extra`. Both answer the same question: what does the optimizer intend to do?

`EXPLAIN ANALYZE` answers a different question: what actually happened? PostgreSQL executes the statement and adds actual startup and total time, actual rows, and loops for every node; with `BUFFERS` it also reports shared hits, reads, dirtied blocks, and temporary I/O. MySQL 8.0.18 and later prints an iterator tree with actual time and row counts. The most valuable comparison is estimated rows against actual rows. A factor of two is normal; a factor of a thousand means the plan was built on a wrong model of the data, and every downstream decision — join order, join algorithm, memory allocation — inherits that error.

`EXPLAIN ANALYZE` executes the statement, so treat it as a write when the statement writes. Wrap it in a transaction and roll back, run it on a restored copy, or use plain `EXPLAIN` when execution is not safe. Before optimizing anything, find the statement that deserves attention with `pg_stat_statements` in PostgreSQL or `performance_schema` in MySQL, sorted by total execution time rather than average time. A two-millisecond query called a million times matters more than a slow report called twice a day.

## Sequential scans, index scans, and when a full scan wins

A sequential scan reads every page of the table. It is not automatically a bug: for a small table, a predicate that matches most rows, or an analytics query that needs almost every column, reading pages in physical order is cheaper than chasing random references. An index scan traverses a B-tree, finds matching entries, then fetches heap or clustered rows; it wins when the predicate is selective enough that those fetches are few.

The planner compares costs using constants such as `seq_page_cost` and `random_page_cost`. PostgreSQL's default ratio of 4:1 assumes spinning disks. On SSDs many teams lower `random_page_cost` to roughly 1.1 after measuring, which makes index scans more attractive, but changing it globally without a benchmark is just a different guess. A bitmap index scan sits between the two: it collects matching entries, sorts heap access by block, and is useful for medium selectivity where a plain index scan would cause too much random I/O.

| Access path | What it reads | Best when | Watch out for |
| --- | --- | --- | --- |
| Sequential scan | every page of the table | small tables or predicates matching a large fraction | assuming it is always a bug |
| Index scan | index entries plus matching rows | highly selective predicates, few rows | random I/O and repeated heap fetches |
| Bitmap index scan | index entries, then rows in block order | medium selectivity with many matches | bitmap memory limits and lost ordering |
| Index-only scan | the index alone | covering queries on well-vacuumed tables | bloat and old snapshots hide visibility |

InnoDB adds a detail that changes index economics: a secondary index stores the primary key, so a lookup that is not covered performs a second traversal into the clustered index. Every index also taxes writes, because each `INSERT`, `UPDATE`, and `DELETE` must maintain every affected entry. Unused indexes are pure overhead. Check `pg_stat_user_indexes` in PostgreSQL or `sys.schema_unused_indexes` in MySQL before adding another one, and remember that a new index is a hypothesis, not a fix.

## Composite index column order and the leftmost prefix

A composite index is a contract about order. An index on `(customer_id, created_at, status)` can serve predicates on `customer_id`, on `customer_id` plus `created_at`, and on all three. It cannot efficiently serve a query that filters only on `created_at`, because the leading column is missing. A range on the second column also limits how the third column can be searched, although the index order can still help sorting and filtering.

Design the order from query patterns: equality columns first, range columns next, and sort columns last. The common advice to put the most selective column first is a myth when it conflicts with equality; an equality predicate on a low-cardinality column followed by a selective range is usually the better arrangement. When several queries compete, prefer an index that serves the most expensive one and accept a filter for the rest, rather than creating near-duplicate indexes that all slow down writes. Indexes on `(a, b)` and `(a)` are redundant.

Sargability decides whether the index is usable at all. A function around the column, an implicit cast, arithmetic on the column, or a leading wildcard hides the indexed value from the optimizer. Rewriting the predicate as a range often restores the index without changing semantics:

```sql
-- Wrapping the indexed column hides it from the index
SELECT id FROM orders WHERE date_trunc('day', created_at) = DATE '2026-11-17';

-- Sargable range; the (customer_id, created_at) index can serve it
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 42
  AND created_at >= TIMESTAMPTZ '2026-11-17 00:00:00+00'
  AND created_at <  TIMESTAMPTZ '2026-11-18 00:00:00+00'
ORDER BY created_at DESC
LIMIT 20;
```

If a rewrite is impossible, an expression index can match the exact expression, but it only helps queries that use the same expression and it needs its own statistics. Newer releases can occasionally skip a low-cardinality leading column, but that is an optimization, not a design rule. Format the candidate statement with the [SQL formatter](/tools/sql-formatter) so reviewers compare plan shapes and predicates rather than whitespace.

## Covering indexes and index-only scans

A covering index contains every column a query reads, so the executor can answer from the index without visiting the table. PostgreSQL calls this an index-only scan, and it works only when the visibility map marks the relevant pages all-visible; a table with heavy write traffic and insufficient vacuum will still visit the heap. Since PostgreSQL 11, `INCLUDE` adds payload columns without making them part of the B-tree key. InnoDB has no separate include clause, but a secondary index implicitly carries the primary key, and additional columns can be added to the index itself.

Coverage is a trade, not a free win. Wider entries mean fewer per page, more write amplification, more WAL or redo, and more cache pressure. Build a covering index for a hot query that repeatedly reads the same small set of columns, not for every query that mentions a column. `SELECT *` defeats coverage entirely: it forces a heap fetch for columns the index does not carry, transfers more data, and breaks when the schema changes. Select the columns the page actually renders.

The same discipline applies to index count. Five overlapping indexes may cover ten query shapes, but each write maintains all five and the planner has more ways to choose badly. Measure index usage after a deployment window long enough to include weekly reports, then drop indexes with zero scans and no constraint behind them.

## Selectivity, statistics, and cardinality estimates

Selectivity is the fraction of rows a predicate passes. A highly selective predicate matches few rows and is a good index candidate; a predicate matching most of the table usually is not. The optimizer estimates selectivity from statistics: `ANALYZE` in PostgreSQL samples the table and fills `pg_stats` with distinct counts, most-common values, histograms, and physical correlation; `ANALYZE TABLE` in MySQL refreshes the cardinality that `information_schema.STATISTICS` reports.

Statistics go stale after bulk loads, large deletes, and data backfills, and stale statistics produce bad plans long before anyone notices a slow query. Skew is the harder problem: a column may have one value in eighty percent of rows and thousands of rare values. A histogram and a most-common-value list handle that case, but correlation between two columns does not fit either structure. PostgreSQL extended statistics (`CREATE STATISTICS ... (dependencies, ndistinct)`) can model it, and expression indexes need `ANALYZE` like any other index.

The diagnostic is always the same: compare estimated and actual rows in `EXPLAIN ANALYZE`. A consistent overestimate or underestimate points to statistics, a type mismatch, or a predicate the optimizer cannot reason about. Fix the estimate before forcing a plan; most bad plans are symptoms, not causes.

## N+1 queries and the cost of round trips

An N+1 pattern loads a list of parents with one query, then issues one query per parent to load a child collection. Two hundred orders become two hundred and one round trips. Each query may be fast, but latency, connection checkout, parsing, and result serialization repeat two hundred times, and the database spends most of its time waiting rather than working.

The fix is to batch. A join with aggregation returns parents and children together, a second query with `WHERE parent_id IN (...)` loads all children in one round trip, and a data-loader pattern coalesces requests within a request boundary. Joining several collections at once multiplies rows into a cartesian product, so split those into separate batched queries or aggregate children as JSON. Measure query count per request in development and in production traces; a sudden rise usually means an eager-loading setting was lost in a refactor.

The same arithmetic explains why connection pools and network topology matter. A query that takes two milliseconds on a local socket costs far more across an availability zone, and a pool smaller than the concurrency limit turns latency into queue time. Optimize the number of round trips before micro-optimizing each statement.

## Pagination that stays fast: offset versus keyset

`LIMIT ... OFFSET n` walks past `n` rows before returning a page. The index may serve the ordering, but the work still grows with the offset, and deep pages become progressively slower. `OFFSET 100000` is a common incident because it looks harmless in code review and passes on a small test database.

Keyset pagination filters on the last row instead of counting rows. With a stable order on `(created_at, id)`, the next page asks for rows where the tuple is smaller than the last seen tuple, orders by the same tuple, and fetches a fixed limit. The corresponding index must match the filter and order columns, and `id` supplies the unique tiebreaker that prevents duplicates or gaps when timestamps collide. Keyset pages cost roughly the same at any depth, but they cannot jump to an arbitrary page number; offer next and previous navigation or an approximate jump instead.

Count queries deserve separate suspicion. `COUNT(*)` over a large table scans index or table pages, and running it for every page doubles the cost of pagination. Cache the total, compute it only when the UI needs it, or use an approximate count for "about 12,000 results" and an exact count only in exports. In MySQL, `LIMIT` with a large offset has the same shape of problem and the same keyset remedy.

## Joins, join order, and misestimated cardinality

The executor has three main join strategies. A nested loop is excellent when the outer side is small and the inner side has an index; it becomes a disaster when the outer side is large and the inner side is scanned repeatedly. A hash join builds a hash table from the smaller input and probes it once per row from the other side, which suits large unsorted inputs. A merge join reads both inputs in sorted order and is efficient when the sort is already provided by an index.

The planner chooses among these using cardinality estimates, so a misestimate does not just change a number in the plan; it can turn a hash join into a nested loop with a million iterations. Read `loops` and rows per loop, not only total time. In PostgreSQL, hash joins that exceed `work_mem` spill to batches, visible as a batch count above one; raise the memory for the session or fix the estimate rather than setting a huge global value. In MySQL, `EXPLAIN` shows access types such as `eq_ref`, `ref`, `range`, and `ALL`, and `Extra` reports `Using join buffer (hash join)` or a temporary table.

Join keys must have compatible types. An implicit cast on the join column can prevent index use, and a function on either side has the same effect. Index the inner side of the join, confirm that the chosen join order matches the data, and use hints only after reproducing the problem with `EXPLAIN ANALYZE`; a forced plan that is faster today can be wrong after the next data growth.

## Parameter sniffing, plan caching, and long transactions

PostgreSQL prepares a statement, uses custom plans for the first executions, and then may switch to a generic plan built without the actual parameter values. For uniform data the difference is small. For skewed data the generic plan is optimized for average selectivity, so a value matching almost nothing may get a sequential scan and a value matching almost everything may get a nested loop. This is parameter sniffing. `plan_cache_mode` can force custom or generic behavior per session, but the better fix is often to make the query plan-stable or to split the rare and common cases into separate statements.

MySQL server-side prepared statements and ORM-level prepares have analogous behavior: the plan is cached until statistics, schema, or settings change. When a query suddenly changes plan after a statistics refresh, compare the old and new estimates before blaming the database. Re-prepare deliberately, and do not disable plan caching globally to fix one statement.

Long transactions distort performance in a different way. An open transaction holds a snapshot, and in PostgreSQL it prevents vacuum from removing dead tuples, so tables and indexes grow, scans read more pages, and every query becomes slower. InnoDB holds row locks and, at `REPEATABLE READ`, gap locks that block inserts. An `UPDATE` or `DELETE` without a usable index scans and locks far more rows than intended. Monitor `pg_stat_activity` for `idle in transaction`, `pg_locks`, `information_schema.innodb_trx`, and `performance_schema.data_locks`; keep transactions short, never wait on a network call inside one, and batch large deletes.

Measurement has its own traps. A single cold-cache run measures disk latency, not production behavior; a single warm run hides the cost of the first request after a deploy. Report both, use production-scale data, and add concurrency before declaring victory. If the benchmark does not include writes, it cannot show the cost of the new index.

## Verification checklist for query plans with pass criteria

A performance fix is complete only when the evidence is reproducible. Run the statement twice with `EXPLAIN (ANALYZE, BUFFERS)`, record estimated and actual rows, then check index usage, write cost, and lock behavior in the same session:

```bash
# Run the plan twice: the second run shows warm-cache behavior
psql "$DATABASE_URL" -c "EXPLAIN (ANALYZE, BUFFERS) SELECT id, total FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20"

# Indexes that are never scanned are pure write overhead
psql "$DATABASE_URL" -c "SELECT relname, indexrelname, idx_scan FROM pg_stat_user_indexes ORDER BY idx_scan ASC LIMIT 20;"

# Long transactions block vacuum and hold locks
psql "$DATABASE_URL" -c "SELECT pid, state, now() - xact_start AS age, wait_event_type, wait_event FROM pg_stat_activity WHERE xact_start IS NOT NULL ORDER BY age DESC LIMIT 10;"
```

Treat the change as passed only when every relevant row below holds. The [SQL to JSON](/tools/sql-json) converter turns a representative result set into fixtures, and [JSON to SQL](/tools/json-to-sql) generates seed rows when the verification needs a disposable database at realistic scale.

| Check | How to test | Pass criteria |
| --- | --- | --- |
| Plan shape | `EXPLAIN (ANALYZE, BUFFERS)` before and after | No unexpected sequential scan on a large table; actual rows within a small factor of estimates |
| Index use | `EXPLAIN` plus `pg_stat_user_indexes` or `EXPLAIN` in MySQL | The intended index appears in the plan and its scan count rises |
| Sargability | Inspect every predicate on an indexed column | No function, cast, or arithmetic wraps the column in the filter |
| Warm and cold behavior | Run the statement twice on the same connection | Warm run shows shared hits; cold and warm latency are both recorded |
| Write cost | Benchmark inserts and updates with and without the index | Write throughput regression is measured and accepted |
| Pagination depth | Request the last page and a keyset page | Keyset latency stays flat; no `OFFSET` above the agreed ceiling |
| N+1 count | Count queries per request in traces | Query count is constant, not proportional to the number of parents |
| Lock waits | Check `pg_stat_activity` and `innodb_trx` under load | No long `idle in transaction`; lock waits stay below the alert threshold |
| Statistics freshness | Inspect estimate error after a bulk load | Estimates remain within the agreed factor after `ANALYZE` |
| Regression | Compare total time in `pg_stat_statements` or `performance_schema` | The target query improves without a new slow query elsewhere |

The rule that prevents most regressions is to change one variable at a time. Add one index, measure write throughput as well as read latency, and keep the change only if both acceptable. Verify on data that resembles production, with the same parameter distribution and concurrency, and record the evidence next to the migration so the next engineer can reproduce it.

## Frequently asked questions

### Does EXPLAIN ANALYZE modify data?

It executes the statement, so an INSERT, UPDATE, or DELETE really applies its changes. In PostgreSQL, wrap the statement in a transaction, run EXPLAIN ANALYZE, and roll back; or run it against a restored copy. Plain EXPLAIN only plans the statement and does not touch data.

### Why does PostgreSQL ignore my index and use a sequential scan?

The predicate probably matches a large fraction of the table, the table is small, statistics are stale, or the cost model overprices random reads. Run ANALYZE, compare estimated with actual rows, and test enable_seqscan=off in a session to confirm the index is usable before changing server-wide costs.

### Is a covering index always faster?

No. A covering index removes heap lookups for one read pattern but makes every write maintain wider entries and consumes more cache. It is a good trade only when a hot query repeatedly reads the same columns and the write cost is acceptable.

### Why are prepared statements slower for some parameter values?

A cached generic plan is built for average selectivity, so values that match almost nothing or almost everything can get the wrong join order or scan type. This is parameter sniffing. Compare custom and generic plans, then force a custom plan for skewed statements or rewrite the query to be plan-stable.

### How do I paginate a large table without slow offsets?

Use keyset pagination: filter on the last seen sort key with a unique tiebreaker, order by the same tuple, and fetch a fixed limit. OFFSET walks past every skipped row, so page ten thousand costs far more than page one even when the index is used.

## References

- [PostgreSQL: Using EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html)
- [MySQL: EXPLAIN Output Format](https://dev.mysql.com/doc/refman/8.4/en/explain-output.html)
- [Use The Index, Luke](https://use-the-index-luke.com/)
- [PostgreSQL: Indexes](https://www.postgresql.org/docs/current/indexes.html)

---

- Canonical: https://www.jsonmind.com/guides/sql-query-performance
- Locale: en
- Published: 2026-11-17
- Updated: 2026-11-17
- Tools: sql-formatter, sql-json, json-to-sql