How to Optimize Database Indexes
Design composite, covering and partial indexes from the queries you actually run, and drop indexes you do not need.
On this page
Introduction
An index is a trade: it makes the queries that use it faster and makes every write slower, because each insert and update must maintain it. Adding indexes by reflex produces a database that is fast for the wrong queries and slow to write for all of them. Optimising indexes is about designing them from the queries you run, ordering the columns to match how the query filters and sorts, letting an index cover a query so it never touches the table, and removing indexes that no query uses. This article covers reading the plan, composite column order, covering and partial indexes, and index hygiene.
How an Index Is Used
A B-tree index supports equality, range and ordering on its leading columns. The planner uses it when the predicate matches the leading column, and it can use a later column only if the earlier ones are constrained by an equality. An index on (a, b) helps a query filtering on a and b, or on a alone, but not on b alone. This is why column order is the central decision in a composite index.
The planner chooses an index when its cost estimate says the index scan is cheaper than a sequential scan, which depends on selectivity and statistics. A predicate that matches most of the table is faster as a sequential scan, so an index on a low-selectivity column may never be used. Verify with the plan rather than assuming.
Reading the Plan for Index Usage
EXPLAIN ANALYZE shows which index the planner chose, how many rows it estimated versus actually read, and whether it fell back to a sequential scan. A query that reads many more rows than it returns is filtering late; a filter that appears as a Filter rather than an Index Cond was not used by the index. These are the signals that an index is missing or misordered.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = $1
AND status = 'open'
ORDER BY created_at DESC
LIMIT 20;
-- Look for:
-- Index Scan using idx_orders_customer_created
-- Index Cond: (customer_id = ...)
-- Filter: (status = 'open') <- filtered, not indexed
-- Rows Removed by Filter: 4000 <- wasted work
-- => a better index includes status.
Composite Index Column Order
Order columns by how the query uses them: equality columns first, then range or sort columns. For a query filtering on customer_id and status and ordering by created_at, the index (customer_id, status, created_at) lets the planner seek on the two equalities and read the rows already ordered by created_at, so no separate sort is needed.
-- Matches the query: equality on customer_id and status, order by created_at.
CREATE INDEX idx_orders_customer_status_created
ON orders (customer_id, status, created_at DESC);
-- The same index also serves a query filtering only on customer_id (leading
-- column), but not one filtering only on status (not the leading column).
-- For that, a separate index is required:
CREATE INDEX idx_orders_status ON orders (status);
Covering and Index-Only Scans
If the index contains every column the query needs, the planner can answer it from the index without reading the table, which is an index-only scan and is much faster for large tables. Add the extra columns with INCLUDE so they are stored in the index but not used for ordering, keeping the search keys clean.
A covering index is wider and costs more to maintain, so add included columns only when the query is hot and the table is large. Check that the index is actually used for an index-only scan; if the table’s visibility map is not current, the index still has to visit the table, and the benefit is smaller.
-- Covering index: search keys for filtering/ordering, INCLUDE for output.
CREATE INDEX idx_orders_covering
ON orders (customer_id, status, created_at DESC)
INCLUDE (id, total);
-- A query selecting id and total can now be answered from the index alone:
SELECT id, total
FROM orders
WHERE customer_id = $1 AND status = 'open'
ORDER BY created_at DESC
LIMIT 20;
-- Plan shows: Index Only Scan using idx_orders_covering
Partial and Expression Indexes
A partial index covers only the rows matching a predicate, which makes it smaller and cheaper to maintain. It is ideal when a query always filters to a small subset, such as only open orders or only non-deleted rows. The predicate in the query must match the index predicate for the planner to use it.
An expression index covers a computed value, such as lower(email) or a JSON field, so a query on the expression can use an index. This makes a case-insensitive lookup possible with a plain index on the lowercased value, and it lets a filter on a JSON key be indexed. The query must use the same expression as the index.
-- Partial index: only open orders, small and cheap to maintain.
CREATE INDEX idx_orders_open_created
ON orders (created_at DESC)
WHERE status = 'open';
-- Query must repeat the predicate: WHERE status = 'open' AND ...
-- Expression index: case-insensitive email lookup without citext.
CREATE INDEX idx_users_email_lower ON users (lower(email));
-- Query must use the same expression: WHERE lower(email) = lower($1)
-- Expression index on a JSON field for a common filter.
CREATE INDEX idx_events_kind ON events ((payload ->> 'kind'));
Too Many Indexes
Every index slows every write and consumes space, so an unused index is pure cost. Find indexes with no scans in the statistics view, or with a very low ratio of scans to writes, and drop them after confirming nothing relies on them. A table with ten indexes can be slower to write than one with three, for no read benefit.
Duplicate indexes are common: (a) and (a, b) overlap, and the shorter one is often redundant unless it is used alone frequently. Review the index list as part of schema design, not as an afterthought, and treat adding an index as a decision with a write cost rather than a free optimisation.
Conclusion
Optimise indexes by working from the queries you run: order composite columns with equality first and sort last, add INCLUDE columns to make a hot query index-only, use partial and expression indexes for filtered and computed predicates, and verify each with the plan. Then remove the indexes no query uses, because each one taxes every write. The result is a set of indexes that match the workload instead of a reflexive collection that slows writes for reads nobody makes.
Sources: PostgreSQL: indexes, PostgreSQL: index-only scans, Use the Index, Luke!.
FAQ
- What order should composite index columns be in?
- Equality columns first, then range or sort columns. The index can use a later column only if the earlier ones are constrained by equality, so put the columns that the query filters with equality at the front and the ordering column at the end.
- Does a covering index always avoid reading the table?
- Not always. An index-only scan also depends on the table visibility map being current; if it is not, the database still visits the table to confirm visibility, and the benefit is smaller. Verify the plan shows an index-only scan.
Report a problem with this articleOpens a pre-filled issue on GitHub.