Skip to content

SQL query performance: execution plans and indexes in practice

B2Bnetwork team · · 6 min

System performance

In brief

You fix a slow SQL query by reading its execution plan: in PostgreSQL with EXPLAIN (ANALYZE, BUFFERS), in SQL Server with the actual execution plan. The plan shows how the database reads, joins and sorts tables, and how many rows it expected versus how many it got. The biggest gains usually come from three things: a composite index with columns ordered equality first, then range; a condition written so the index can be used; and current statistics. Verify every change on production-scale data.

What an execution plan is

An execution plan is the recipe the database follows to run a query: the order in which it reads tables, the access method (full scan or index), and how it joins, filters, groups and sorts. The optimizer builds it from the query, the schema with its indexes, and statistics about the data, as the SQL Server documentation describes. PostgreSQL works the same way: the planner estimates the cost of several alternatives and picks the cheapest.

Hence the key rule: the same SQL can get a different plan in testing and in production, because table sizes and data distribution differ. Look at plans on data close to production size; preparing it without violating GDPR is covered in the article on test data and GDPR.

In PostgreSQL, plain `EXPLAIN` shows the plan and estimates, while `EXPLAIN (ANALYZE, BUFFERS)` also runs the query and reports actual times, row counts and pages read. Because ANALYZE really executes the statement, the documentation shows INSERT, UPDATE and DELETE inside a transaction that ends with ROLLBACK.

How to read an execution plan

Read the plan from the most indented nodes, because they run first. The most common operations:

Operation (PostgreSQL)What it meansWhen to worry
Seq Scanreads the whole tablea large table, yet the result is a few rows
Index Scanindex lookup, then reading rows from the tablemany thousands of random table reads
Index Only Scanthe whole result comes from the indexrarely a problem, usually the goal
Bitmap Heap Scancollects addresses from the index, then reads pagesmany pages for a small result
Nested Loopfor each row on the left, a lookup on the righta high loop count with no index on the right
Hash Joina hash table built from the smaller sidethe hash table does not fit in memory
Sortsorts the resultsorting on disk instead of in memory

Three signals point to a problem fastest: a large gap between estimated (`rows`) and actual row counts, usually caused by stale or coarse statistics; a high `loops` count in a nested loop; and many pages read (`Buffers: shared read`) for a small result.

Indexes that actually help

A B-tree index helps when a query selects a small part of a table or needs data in index order. In a composite index, column order decides everything. The PostgreSQL documentation explains that a multicolumn index is most efficient with constraints on the leading columns: equality on the first columns plus an inequality on the first column without equality narrow the part of the index that is scanned.

An example from a telecom billing system: a customer's invoices from the last 90 days, newest first.

-- query
SELECT number, issue_date, amount
FROM invoices
WHERE customer_id = $1
  AND issue_date >= now() - interval '90 days'
ORDER BY issue_date DESC
LIMIT 20;

-- index: equality first, then the range, and the result columns in INCLUDE
CREATE INDEX CONCURRENTLY invoices_customer_date_idx
  ON invoices (customer_id, issue_date DESC)
  INCLUDE (number, amount);

The equality column (`customer_id`) comes first and the range and sort column (`issue_date`) second, so the database reads only a slice of the index and does not sort. INCLUDE adds columns not used for searching that let the query be answered from the index alone. A partial index (`CREATE INDEX ... WHERE status = 'open'`, open invoices only) covers just the rows applications ask for and can be much smaller.

Every index slows writes and takes space. Add one for a specific query from the most expensive list, described in the article on database bottlenecks, not just in case.

Why the database ignores an existing index

  • A function on the column. `WHERE lower(email) = ...` or `WHERE date(created_at) = ...` will not use a plain index on the column. A range condition or an expression index helps.
  • Mismatched types. Comparing a text column with a number, or different types in a join, forces a conversion and blocks the index.
  • A leading wildcard. `LIKE '%smith'` cannot use a B-tree; text search needs other index types.
  • Low selectivity. When a condition selects a large part of the table, a full scan is cheaper and the optimizer rightly picks it.
  • Column order. An index on `(date, customer_id)` does little for a query filtering on `customer_id` alone.
  • Pagination with OFFSET. `OFFSET 100000` makes the database read and discard a hundred thousand rows. Keyset pagination (`WHERE date < last_date`) uses the index.

Statistics and safe changes in production

The optimizer is only as good as its statistics. In PostgreSQL they are gathered by ANALYZE, which also runs automatically, with detail set by default_statistics_target (100 by default) or ALTER TABLE ... SET STATISTICS per column. When columns are correlated, such as city and postal code, the planner multiplies their selectivities and underestimates rows; extended statistics from CREATE STATISTICS help.

A plain CREATE INDEX blocks writes to the table while it builds. The CONCURRENTLY option lets writes continue, although the build takes longer and needs two passes over the table, which is why the documentation recommends it for adding indexes in production. A safe order of work:

  1. Take a query from the most expensive list and its parameters from real traffic.
  2. Capture the plan with ANALYZE on production-scale data.
  3. Change one thing: an index, a condition or statistics.
  4. Compare the plan and timing, then rerun the load test, because fixing one query reveals the next.
  5. Deploy the index with CONCURRENTLY and check the plan in production.

When moving a system to another database, plans have to be checked again, as we describe in the article on migrating from Oracle to PostgreSQL. An example of performance testing with query analysis in a billing system is the project on performance testing a billing system.

Questions and answers

What is the difference between EXPLAIN and EXPLAIN ANALYZE?

EXPLAIN shows the plan the optimizer intends to run, with estimated costs and row counts, without executing the query. EXPLAIN ANALYZE runs the query and adds actual times and row counts. The gap between estimate and reality is the most valuable information in the plan. Run statements that change data with ANALYZE inside a transaction rolled back with ROLLBACK.

In what order should columns go in a composite index?

Columns compared with equality first, then the column used for a range or sorting. The index works best when the query has conditions on the leading columns. If different queries filter on different sets of columns, two well-matched indexes are better than one wide index that fits none of them.

Why is the same query fast in testing and slow in production?

Because the plan depends on table sizes, data distribution and statistics. On a small database a full scan may be fastest and a missing index does no harm. In production the table has millions of rows, and an uneven distribution, such as a few customers with millions of invoices, produces different plans for different parameters.

How many indexes is too many?

There is no single number. Every index slows INSERT and UPDATE and takes space and memory. Signs of excess are indexes whose usage statistics show zero reads and indexes that duplicate the leading columns of others. Drop them after checking that they do not serve rare but important reports.

What it looks like in a project

Your system slows down under load? We'll find where it loses time.

Let's talk

Read more: System performance