Sub topic 11
Choosing an Index Type for Your Workload
What this chapter assumes
This chapter assumes you have read the earlier chapters on B-tree, hash, GIN, GiST, and BRIN indexes, operator classes, and EXPLAIN (ANALYZE, BUFFERS). It does not teach those again. It gives you a repeatable way to pick among them, and to decide whether to add an index at all.
Start from the query, not the index
An index type is a promise about which operators it can answer. So the choice starts with the WHERE, JOIN, and ORDER BY clauses your application actually runs. For each important query, write down three things:
- The operator in the predicate (
=,<,BETWEEN,@>,@@,&&,<->,ILIKE '%x%'). - The column type (scalar, array,
jsonb, range, geometry, text). - How the table's physical order relates to the column (random or naturally ordered).
Then ask how often the query runs and how many rows it returns. An index only pays off if the query is selective, which means it keeps a small fraction of the table. If a query returns 40% of the rows, the planner will usually prefer a sequential scan, and no index type changes that.
Quick reference
| Query shape | First choice | Notes |
|---|---|---|
| `=`, `<`, `>`, `BETWEEN`, `IN`, `ORDER BY` on scalars | B-tree | The default. Also enforces `UNIQUE` and primary keys. |
| Equality on a long value, never ranges or sorting | Hash | Only `=`. A B-tree usually does the same job and also supports ordering. |
| `jsonb @>`, `?`, array `@>` / `&&`, full text `@@` | GIN | Slower writes. No ordering and no index-only scans. |
| `ILIKE '%text%'`, `LIKE '%text%'` | GIN with `gin_trgm_ops` | Needs the `pg_trgm` extension. |
| Left-anchored `LIKE 'abc%'` in a non-C locale | B-tree with `text_pattern_ops` | Not usable for `<`, `>`, or `ORDER BY` in the normal collation. |
| Range overlap `&&`, containment, `<->` nearest neighbor | GiST | Also the only option for exclusion constraints. |
| Range filters on a huge, append-mostly, time-ordered table | BRIN | Tiny, but only helps when physical order matches column order. |
| Function result, such as `lower(email)` | B-tree expression index | The query must use the same expression. |
| Hot query touching a small subset of rows | Partial B-tree | The index only contains rows matching its `WHERE`. |
A decision path
Working through the common cases
Scalars, ranges, and sorting: B-tree
Reach for a B-tree first. It supports equality, ranges, ORDER BY, LIMIT on ordered data, IS NULL, and uniqueness. Three refinements cover most real workloads:
- Multicolumn. Put equality columns first and the range or sort column last. An index on
(account_id, created_at DESC)servesWHERE account_id = 7 ORDER BY created_at DESC LIMIT 20with no sort step. The same index is nearly useless for a query that filters only oncreated_at. - Partial. If 95% of rows are
closedand your hot path readsopenones, index only those. The index is smaller and cheaper to maintain. - Covering.
INCLUDE (col)stores extra columns in the leaf pages so the query can use an index-only scan. This depends on the visibility map, so tables with heavy churn still visit the heap untilVACUUMcatches up.
Containment and search: GIN
GIN maps each key, array element, or lexeme to the rows containing it. Use it when the question is "which rows contain X?". For jsonb, the default operator class jsonb_ops supports @>, ?, ?|, ?&, and the jsonpath operators. The jsonb_path_ops class supports fewer operators (@> and the jsonpath ones) but produces a smaller, faster index. If you only run @>, prefer jsonb_path_ops.
GIN has a write cost. One inserted row with a 30-element array produces up to 30 index entries. GIN buffers some of this work in a pending list (fastupdate) and merges it during vacuum or when the list grows past gin_pending_list_limit. That keeps average inserts quick but can cause an occasional slow insert.
Overlap, proximity, and constraints: GiST
Choose GiST when values have a spatial or interval character. It supports range && and @>, geometric operators, and nearest-neighbor ordering with <->. It is also the only built-in type that can back EXCLUDE USING gist constraints. Use btree_gist to mix scalar columns such as room_id WITH = into the same constraint.
Huge, ordered tables: BRIN
BRIN stores a summary (min and max) per block range. It works when the column's values correlate with physical row position, which is typical for created_at on an append-only table. Check before you build:
SELECT attname, correlation
FROM pg_stats
WHERE tablename = 'ticket_events'
AND attname = 'recorded_at';A correlation near 1 or -1 means BRIN is a good fit. A value near 0 means each block range spans most of the value range, so BRIN cannot skip anything. Updates or deletes that scatter rows (for example, reused free space after bulk deletes) degrade correlation over time.
Equality on long values: hash
Hash indexes are crash-safe and replicated since PostgreSQL 10. They store a 4-byte hash of the value, so for long keys such as 200-character tokens they can be smaller than a B-tree. They cannot enforce uniqueness, cannot be multicolumn, and cannot sort. Treat them as a niche optimization that you confirm with measurements, and use a B-tree otherwise.
A worked example
Suppose a support-ticket system runs these queries. Each one gets its own index, chosen from the operator it uses.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE tickets (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
account_id bigint NOT NULL,
status text NOT NULL,
subject text NOT NULL,
tags text[] NOT NULL DEFAULT '{}',
meta jsonb NOT NULL DEFAULT '{}',
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE ticket_events (
ticket_id bigint NOT NULL,
kind text NOT NULL,
recorded_at timestamptz NOT NULL DEFAULT now()
);
-- Q1: newest open tickets for one account
-- WHERE account_id = $1 AND status = 'open' ORDER BY created_at DESC LIMIT 20
CREATE INDEX tickets_open_account_idx
ON tickets (account_id, created_at DESC)
WHERE status = 'open';
-- Q2: tickets with a tag
-- WHERE tags @> ARRAY['billing']
CREATE INDEX tickets_tags_gin_idx
ON tickets USING gin (tags);
-- Q3: tickets by channel stored in jsonb
-- WHERE meta @> '{"channel": "email"}'
CREATE INDEX tickets_meta_gin_idx
ON tickets USING gin (meta jsonb_path_ops);
-- Q4: substring search in subject
-- WHERE subject ILIKE '%refund%'
CREATE INDEX tickets_subject_trgm_idx
ON tickets USING gin (subject gin_trgm_ops);
-- Q5: daily rollups over an append-only event log
-- WHERE recorded_at >= now() - interval '1 day'
CREATE INDEX ticket_events_recorded_brin_idx
ON ticket_events USING brin (recorded_at);Two details matter here. Q1 uses a partial index, so the index excludes every closed ticket and stays small as history grows. Q5 uses BRIN instead of B-tree because the log is append-only, and a B-tree on a billion-row table can reach tens of gigabytes while the BRIN stays in the megabytes.
After loading realistic data, confirm each choice with EXPLAIN (ANALYZE, BUFFERS). Look for the expected index node, and compare Buffers: shared hit/read against the sequential scan alternative.
The cost side of the decision
Every index is paid for on every write and in storage. Weigh these before adding one:
- Inserts and deletes update every index on the table.
- Updates that change an indexed column, or that cannot fit the new row version on the same page, add new entries to every index. Updates that change no indexed column can use heap-only tuples (HOT) and skip index maintenance. An unneeded index on a frequently updated column removes that shortcut.
- Space and cache. Indexes compete with table data for
shared_buffersand the OS cache. A rarely used 20 GB index can push hot pages out of memory. - Build and rebuild time. Large GIN and B-tree builds take minutes to hours.
Use the statistics views to prune. Create indexes without blocking writers, and review usage regularly:
CREATE INDEX CONCURRENTLY tickets_account_idx ON tickets (account_id);
SELECT indexrelname,
idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE relname = 'tickets'
ORDER BY idx_scan;CREATE INDEX CONCURRENTLY cannot run inside a transaction block. If it fails or is cancelled, it leaves an INVALID index behind. That index still adds write cost and must be dropped before you retry. Find such indexes with SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;.
Common errors
- Indexing every column "just in case." This slows writes and rarely helps. Index for named queries.
- Wrong column order in a multicolumn index. The leading column decides which queries can use the index efficiently. Equality columns go before range columns.
- Expression mismatch. An index on
lower(email)does not serveWHERE email = '[email protected]'. The query must containlower(email). - Default operator class mismatch. A plain B-tree on a text column in a non-C locale will not serve
LIKE 'abc%'. Usetext_pattern_ops, or usegin_trgm_opsfor substring search. - BRIN on shuffled data. It builds fine and then does nothing. Check
correlationfirst. - GIN for a single-key lookup. If you always query
meta->>'channel' = 'email', an expression B-tree index on(meta->>'channel')is smaller and faster than a GIN over the whole document. - Trusting a tiny test table. On a few hundred rows the planner correctly picks a sequential scan. Test with production-sized data, and use
SET enable_seqscan = offonly to learn whether an index could be used, never as a fix. - Stale statistics. After a bulk load, run
ANALYZEso the planner's row estimates match reality.
Exercises
Exercise
A query runs WHERE account_id = 7 AND created_at >= now() - interval '7 days' ORDER BY created_at DESC. Which index would you create, and why does column order matter?
Show answer
Create a B-tree on (account_id, created_at DESC). The equality column account_id comes first, so the index narrows to one account's entries, and within them the entries are already ordered by created_at, giving both the range filter and the sort without a separate sort step. Reversing the order would make the index much less useful for this query, because entries for one account would be scattered across the index.
Exercise
A 2 TB append-only sensor_readings table is filtered by recorded_at ranges. A B-tree on recorded_at is 60 GB. What do you check before replacing it with BRIN, and what result tells you BRIN will work?
Show answer
Check correlation for recorded_at in pg_stats. A value close to 1 (or -1) means row order on disk follows the column order, so each block range's min/max summary covers a narrow slice and BRIN can skip most ranges. A value near 0 means BRIN would rarely skip anything. Also confirm that rows are not regularly updated or deleted in ways that scatter physical order.
Exercise
Your team wants to speed up WHERE payload @> '{"type": "login"}' on a jsonb column and asks whether to use jsonb_ops or jsonb_path_ops. What do you recommend and what is the trade-off?
Show answer
If the application only uses @> (and jsonpath operators), use a GIN index with jsonb_path_ops. It is typically smaller and faster. The trade-off is that it does not support key-existence operators such as ?, ?|, and ?&. If you need those, use the default jsonb_ops.