How-To Guide

How to Optimize SQL Joins with the Right Indexes

Speed up SQL joins by indexing the join keys and filter columns, choosing a join strategy, and giving the planner the statistics it needs.

On this page

  1. Introduction
  2. Index the join keys
  3. Order composite indexes to match the query
  4. Give the planner accurate statistics
  5. Verify the join strategy
  6. Test the plan for critical joins
  7. Common pitfalls
  8. Conclusion

Introduction

A join is a logical operation that the database implements with one of several physical strategies, and how fast it runs depends on indexes and statistics as much as on the query text. The same join can be a near-instant nested loop that probes an index a few hundred times or a slow sequential scan that reads both tables in full. Understanding how the planner chooses between them is how you make a join fast instead of hoping.

This tutorial covers indexing the join keys, ordering composite indexes to match the query, giving the planner accurate statistics, and reading the plan to confirm the chosen strategy matches the data. The examples use PostgreSQL, but the reasoning applies to any query planner that offers nested loop, hash, and merge joins.

Index the join keys

The join key is the column the two tables match on. A nested loop join scans the outer side and probes the inner side once per outer row, so the inner side must have an index on the join key, or each probe becomes a scan. A foreign key does not create an index automatically in PostgreSQL, so a table joined frequently on its foreign key needs an explicit index on that column.

Index the outer side too when a filter on the outer side is what drives the join, because the planner may choose to filter the outer side first with an index and then probe. A composite index on (filter_column, join_key) serves both the filter and the join in one structure, which is often better than two single-column indexes. Cover the join key last in the composite so the equality filter can seek and the join key can be read from the same index.

-- orders joins to customers; index the foreign key used in the join
CREATE INDEX CONCURRENTLY idx_orders_customer_id ON orders (customer_id);

-- a filtered join benefits from a composite leading with the filter
CREATE INDEX CONCURRENTLY idx_orders_status_customer
  ON orders (status, customer_id);

Order composite indexes to match the query

A composite index is usable only from its leading columns. Put the equality predicates first, then a range or sort column, then the join key if it is needed only for the lookup. A query that filters status = ‘pending’ and joins on customer_id wants an index on (status, customer_id), not (customer_id, status), because the first allows a seek to the pending slice and then a lookup, while the second forces a scan across all customers.

Ranges come after equalities. An index on (status, created_at) lets the planner seek the status and range-scan the dates, which matches a query filtering both. An index on (created_at, status) cannot use the status for the seek because it is not the leading column after a range. Match the index column order to the query’s filter and sort order, and confirm with EXPLAIN that the index is actually used.

-- supports: WHERE status=$1 AND created_at >= $2 ORDER BY created_at DESC
CREATE INDEX idx_orders_status_created ON orders (status, created_at DESC);

Give the planner accurate statistics

The planner estimates how many rows each side will produce and chooses a strategy from that estimate. If the statistics are stale or too coarse, the estimate is wrong and the plan is wrong. Run ANALYZE after large data changes, and raise the statistics target on columns whose distribution matters, such as a status column with one very common value and many rare ones, so the planner samples more and estimates better.

Extended statistics help when columns are correlated. If city and postal_code always move together, the planner’s independent estimates multiply them and over- or under-count. Creating extended statistics on the correlated columns lets the planner estimate their combination accurately, which can flip a join from a hash to a nested loop or the other way to the faster choice.

ALTER TABLE orders ALTER COLUMN status SET STATISTICS 500;
ANALYZE orders;

-- capture correlation between two columns
CREATE STATISTICS orders_city_postal (dependencies)
  ON city, postal_code FROM orders;
ANALYZE orders;

Verify the join strategy

Read EXPLAIN and identify the join node. A nested loop is right when the outer side is small and the inner side is indexed. A hash join is right when both sides are large and there is no useful index order. A merge join is right when both sides are sorted on the join key, often by indexes. The strategy is not the goal; matching the strategy to the row counts is.

Check the estimated versus actual rows on the join node. A hash join chosen because each side was estimated at a hundred rows but actually produced a hundred thousand means the estimates were wrong, and fixing statistics may switch to a better plan. After any index or statistics change, re-run EXPLAIN and compare buffers to confirm the join does less work.

Hash Join  (cost=... rows=...) (actual time=... rows=...)
  Hash Cond: (o.customer_id = c.id)
  ->  Seq Scan on orders o  (actual rows=95000)   -- estimate was wrong before ANALYZE
  ->  Hash  (actual rows=4000)
-- after ANALYZE + index, expect a nested loop probing customers_pkey instead

Test the plan for critical joins

Add a plan test that runs EXPLAIN on a critical join against a representative dataset and asserts it does not contain a sequential scan on the large side, or that it uses a named index. Assert the join strategy is one of the acceptable ones. This catches a regression where a statistics change or a dropped index flips a fast join to a slow one, and it documents which strategies the team considers acceptable.

psql -d app -c "EXPLAIN (ANALYZE, BUFFERS) SELECT ... FROM orders o JOIN customers c ON c.id=o.customer_id WHERE ...;"
# assert the large table is accessed by an index, and note the join node type

Common pitfalls

Joining on a foreign key with no index, ordering a composite index against the query shape, ignoring stale statistics, disregarding column correlation, and adding an index to both sides blindly without checking the plan are the recurring mistakes. Indexing the join keys, matching composite order to the query, refreshing statistics and adding extended statistics, and reading the plan address them.

Conclusion

A fast join is an index and a statistic that match the query. Index the join key on the inner side, lead composite indexes with the equality filter, refresh and extend statistics so estimates are accurate, then read EXPLAIN to confirm the strategy fits the row counts. Self-check by asserting the large table is reached by an index and that the join node type matches the data. With indexes and statistics aligned, the planner chooses the fast strategy on its own.

Sources: PostgreSQL: Join strategies, PostgreSQL: Index types and multicolumn indexes, PostgreSQL: Statistics used by the planner.

FAQ

Which side of a join needs the index?
In a nested loop the inner side is probed once per outer row, so the inner side needs the index on the join key. Adding it to both sides helps when the planner may swap the sides or when both are filtered.
Why does the planner pick a hash join over an index?
When both sides are large or the filter is not selective, reading both fully and hashing is cheaper than many index lookups. A hash join is not a sign of a missing index; it is often the fastest choice for a large join.

Related Examples