PostgreSQL indexes: B-tree, GIN and partial indexes, validated with EXPLAIN ANALYZE
How to choose between B-tree, GIN, composite and partial indexes in PostgreSQL, read the plan with EXPLAIN ANALYZE, and create indexes without locking production.
In short
Use B-tree (the default) for equality, ranges and sorting; GIN for searching inside jsonb, arrays and full text; and partial indexes when queries always filter the same subset of rows. Before and after creating an index, confirm its effect with EXPLAIN (ANALYZE, BUFFERS), and in production create it with CREATE INDEX CONCURRENTLY so writes aren't blocked.
Start with the execution plan
An index created without measuring is a guess. PostgreSQL shows exactly how it intends to run a query with EXPLAIN, and with EXPLAIN ANALYZE it actually runs the query and reports timings and real row counts for each step.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;
What to read in the output:
- Scan type:
Seq Scanreads the whole table;Index ScanandBitmap Heap Scanuse an index;Index Only Scananswers from the index alone, without touching the table. - Estimated versus actual rows:
rows=in the cost is the estimate;actual ... rows=is reality. Differences of orders of magnitude point to stale statistics; runANALYZE orders. - Rows Removed by Filter: many rows read and discarded is a sign that the filter lacks a suitable index.
- Buffers:
shared hitcame from memory,readcame from disk. This helps separate a slow query from a cold cache.
Careful: EXPLAIN ANALYZE executes the statement. To analyze an UPDATE or DELETE, wrap it in a transaction and undo it with ROLLBACK.
B-tree: the default for almost everything
Without a type, CREATE INDEX creates a B-tree. It handles equality (=), ranges (<, >, BETWEEN), IN, IS NULL, and also avoids sorts, because it keeps values in order.
In composite indexes, column order matters. A B-tree is most efficient when the query constrains the leftmost columns. A rule that works well: columns compared by equality first, then the range or sort column.
-- Serves WHERE customer_id = ? ORDER BY created_at DESC
CREATE INDEX index_orders_on_customer_id_and_created_at
ON orders (customer_id, created_at DESC);
This index also serves queries that filter only by customer_id, but it doesn't help much for queries that filter only by created_at.
Partial indexes for frequent subsets
When queries almost always look at a small fraction of a table, such as pending orders in a table dominated by completed ones, a partial index covers only those rows. It is smaller, fits better in memory and costs less to maintain.
CREATE INDEX index_orders_pending_on_created_at
ON orders (created_at)
WHERE status = 'pending';
-- Uses the index: the query's filter implies the index predicate
SELECT * FROM orders WHERE status = 'pending' AND created_at < now() - interval '1 hour';
The planner only uses a partial index when it can prove that the query's condition implies the index's condition. A generic parameter such as status = $1 in a prepared plan can prevent that.
GIN for jsonb, arrays and text search
A B-tree compares whole values. To ask whether a jsonb document contains a key, whether an array contains an element or whether a text contains words, the right type is GIN, which indexes each inner element separately.
-- jsonb_path_ops: smaller index, supports the containment operator @>
CREATE INDEX index_events_on_payload
ON events USING GIN (payload jsonb_path_ops);
SELECT * FROM events WHERE payload @> '{"type": "signup"}';
The default jsonb_ops class also supports the key-existence operators (?, ?|, ?&); jsonb_path_ops doesn't, but it is usually smaller and faster for containment. Choose based on the queries you actually run.
Creating indexes in production without locking the table
A plain CREATE INDEX blocks writes to the table until it finishes. On large tables that means minutes of stalled inserts and updates. CREATE INDEX CONCURRENTLY avoids the lock, at the cost of taking longer and not being allowed inside a transaction. In Rails:
class AddIndexToOrdersOnCustomerAndCreatedAt < ActiveRecord::Migration[7.1]
disable_ddl_transaction!
def change
add_index :orders, [:customer_id, :created_at],
order: { created_at: :desc },
algorithm: :concurrently
end
end
If a concurrent build fails halfway, PostgreSQL leaves an index marked as invalid. It isn't used by queries, but it is still updated on every write. Drop it with DROP INDEX CONCURRENTLY and try again.
Indexes have a cost
Every index makes INSERT and UPDATE slower and takes disk and memory. It's worth periodically reviewing indexes that are never used:
SELECT relname AS table_name, indexrelname AS index_name, idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;
Before dropping one, confirm that the statistics cover a representative period and that the index doesn't back a UNIQUE constraint.
Indexes fix slow queries, but they don't fix too many queries. If the log shows the same query repeated dozens of times per request, the problem is different: see how to eliminate N+1 queries in Rails. And if you store embeddings in PostgreSQL with pgvector, the same measure-before-you-index principle applies to the vector search described in local RAG with Ollama.
Related writing
All writing-
Software Engineering · · 3 min read
N+1 queries in Rails: how to find them, fix them and keep them from coming back
What the N+1 problem is in Active Record, when to use includes, preload or eager_load, and how strict_loading stops regressions.
-
AI Engineering · · 4 min read
Local RAG with Ollama: how retrieval-augmented generation works
What RAG is, how each stage works (chunking, embeddings, retrieval and generation), and how to build a local, private version with Ollama and Python.
-
Software Engineering · · 4 min read
Uptime monitoring: why you should alert only after consecutive failures
How to build an availability monitor that catches real outages without false alarms: consecutive failures, detection time, states and a C# example.