>_Blogging Programmer~/notes since 2016
blogging-programmer › databases › postgresql-indexes-that-actually-help.md
date: 2026-11-27 topics: [Databases] read: 4 min words: 896

PostgreSQL: Indexes That Actually Help

The first time a query became slow in one of my projects, my fix was to add an index on every column in the WHERE clause. The query got faster. A few months later, inserts had become noticeably slower, and several of those indexes had never been used once.

Indexes are not free. Every index speeds up some reads, costs space, and slows down every insert, update and delete on that table. The goal is not to have many indexes but to have the right ones.

How PostgreSQL Uses a B-tree Index

The default index type in PostgreSQL is a B-tree. It keeps the indexed values sorted, so PostgreSQL can find a value, or a range of values, without reading the whole table.

CREATE INDEX orders_customer_id_idx ON orders (customer_id);

With this index, a query like the following can jump straight to the matching rows:

SELECT * FROM orders WHERE customer_id = 42;

A B-tree helps with equality (=), ranges (<, >, BETWEEN), sorting (ORDER BY) and prefix matches (LIKE 'abc%'). It does not help with LIKE '%abc', because the sorted order says nothing about how values end.

Index What You Filter On, Not Everything You Select

An index is chosen by the WHERE, JOIN and ORDER BY parts of a query, not by the columns in SELECT. Before adding an index, I look at the queries the application actually runs. Most applications have a handful of queries that run constantly, and those are the ones worth optimising.

PostgreSQL can tell you which queries those are. With the pg_stat_statements extension enabled, this lists the queries that take the most total time:

SELECT query, calls, round(total_exec_time) AS total_ms, round(mean_exec_time, 1) AS mean_ms
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

A query that takes 5 ms but runs a million times a day matters more than a 2-second report that runs once a week.

Column Order Matters in Composite Indexes

A composite index covers several columns:

CREATE INDEX orders_customer_created_idx ON orders (customer_id, created_at);

The order of the columns decides which queries it can help. Think of a phone book sorted by last name and then first name. It is useful for finding everyone called “Balić”, and for finding “Balić, Emir”. It is useless for finding everyone called “Emir”.

So this index helps:

-- equality on the first column, range or sort on the second
SELECT * FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

But it does little for a query that filters only on created_at.

My rule of thumb: columns compared with = first, then the column used for a range or sort. An index that matches both the filter and the sort lets PostgreSQL read the first 20 rows in order and stop, instead of sorting thousands.

It also means a separate index on customer_id alone is redundant. The composite index already starts with it.

Partial Indexes for Common Filters

Many tables have a status column where the application mostly cares about a small subset of rows:

SELECT * FROM orders WHERE status = 'pending' ORDER BY created_at;

If 98% of orders are completed, an index on all orders is mostly wasted. A partial index contains only the rows that match a condition:

CREATE INDEX orders_pending_idx ON orders (created_at) WHERE status = 'pending';

It is much smaller, faster to update, and PostgreSQL uses it whenever a query includes the same condition. Partial indexes are one of the PostgreSQL features I wish I had learned about earlier.

They also work well for soft deletes:

CREATE UNIQUE INDEX users_email_active_idx ON users (email) WHERE deleted_at IS NULL;

This enforces unique email addresses among active users while allowing a deleted user’s address to be reused.

Expression Indexes

If a query filters on an expression, an index on the plain column will not help:

SELECT * FROM users WHERE lower(email) = 'ana@example.com';

PostgreSQL can index the expression itself:

CREATE INDEX users_email_lower_idx ON users (lower(email));

The query must use the same expression for the index to be considered.

Covering Indexes

When a query needs only a few columns, PostgreSQL can sometimes answer it from the index alone, without visiting the table. This is called an index-only scan. The INCLUDE clause adds columns to the index that are stored but not used for searching:

CREATE INDEX orders_customer_total_idx ON orders (customer_id) INCLUDE (total);

SELECT customer_id, sum(total) FROM orders WHERE customer_id = 42 GROUP BY customer_id;

This is an optimisation for hot queries, not something to apply everywhere.

Do Not Forget Foreign Keys

PostgreSQL creates an index for primary keys and unique constraints automatically, but not for foreign keys. A table that references customers(id) through customer_id has no index on customer_id unless you create one.

That hurts in two places: joins from customers to orders, and deleting a customer, where PostgreSQL must check for referencing orders. Indexing foreign key columns is one of the few rules I apply almost by default.

Check That the Index Is Used

After creating an index, I confirm that the query uses it:

EXPLAIN ANALYZE
SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20;

If the plan shows Index Scan using orders_customer_created_idx, it works. If it shows Seq Scan, PostgreSQL decided reading the table was cheaper, which is often correct for small tables or queries that return a large share of the rows. I will cover reading these plans in a separate post.

Over time, I also check for indexes that are never used:

SELECT relname AS table, indexrelname AS index, idx_scan
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY relname;

An index with zero scans after weeks of normal traffic is a candidate for removal, unless it enforces a unique constraint.

Creating Indexes on a Live Table

A plain CREATE INDEX blocks writes to the table while it runs. On a large production table, that can mean minutes of failed requests. The concurrent variant avoids that:

CREATE INDEX CONCURRENTLY orders_customer_created_idx ON orders (customer_id, created_at);

It takes longer and cannot run inside a transaction, which matters for some migration tools, but it keeps the application running.

Summary

  • Start from the queries that cost the most total time, not from the table definition.
  • Put equality columns first and range or sort columns last in composite indexes.
  • Use partial indexes when queries focus on a small subset of rows.
  • Index foreign keys.
  • Confirm usage with EXPLAIN ANALYZE, and remove indexes nobody uses.

Fewer, well-chosen indexes have served me much better than one index per column.

No comments yet #Databases PostgreSQLPerformance
Ctrl J