
On this page
- Why is “just add an index” the wrong reflex?
- When is a B-tree index the right call?
- When does a GIN index pay off over a B-tree?
- Is a BRIN index worth using?
- What do partial and expression indexes buy you?
- Can a covering index really let Postgres skip the table?
- What does every index cost you on writes?
- How do you choose the right index type?
- What does a sensible indexing default look like?
- Questions people ask
Slow-query war rooms tend to end the same way. Someone runs EXPLAIN, sees a sequential scan, types CREATE INDEX on whatever column shows up in the WHERE clause, and the ticket gets closed. Sometimes that’s exactly right. Often it’s a coin flip that happened to land well.
The reflex is understandable. “Add an index” is the one piece of database advice everyone has absorbed, so indexes get treated as a single, undifferentiated fix: more indexes, faster queries, done. What that framing misses is that Postgres ships six built-in index types, B-tree, hash, GiST, SP-GiST, GIN and BRIN, and each one is a bet on a specific access pattern. An index that doesn’t match the pattern isn’t a mild inefficiency. It’s pure write tax with no read payoff.
The narrower claim: five tools, B-tree, GIN, BRIN, partial and covering indexes, cover most everyday workloads, as long as you know the one question each answers well. Here’s when each pays off, where each stops, and how to audit what you already have. There’s no universal answer; that’s the whole argument. It picks up where Postgres does more than you think left off.
Why is “just add an index” the wrong reflex?
Because an index isn’t a free lookup table. It’s a second data structure that Postgres has to maintain as rows are inserted, updated and deleted. The read speedup is the visible half of the trade. The invisible half is write amplification, extra WAL, larger backups, longer vacuums, and a planner with more choices to get wrong.
That trade is worth making constantly. Indexes are among the highest-return tools in relational performance work, and nothing here argues otherwise. The argument is about matching, not abstinence. A B-tree on a JSONB column does nothing for containment queries. A GIN index on a plain timestamp column won’t even build without the btree_gin extension, whose docs say it generally won’t outperform a B-tree anyway. The index type has to answer the same question the query asks, or you’ve bought overhead and stored it in production.
The other half of the problem is that indexes get added and never audited. Have you ever seen a migration that drops an index because nobody could prove it was used? A hot table can end up carrying a dozen indexes, some of them redundant prefixes of each other, each one silently taxing writes. The fix for one slow query becomes a permanent line item.
So the working rule for the rest of this article: an index earns its place when you can name the query pattern it serves, and it keeps its place only while pg_stat_user_indexes shows it being scanned.
When is a B-tree index the right call?
Most of the time, which is exactly why it’s the default. A B-tree pays off whenever a query compares whole values with equality or range operators, or sorts by them: WHERE user_id = 42, WHERE created_at >= now() - interval '7 days', ORDER BY created_at DESC. It also backs every primary key and unique constraint, so you already run B-trees whether you chose them or not.
The decision that separates careful schema work from reflex work isn’t whether to use a B-tree. It’s column order in a composite B-tree. Per the multicolumn index rules, equality conditions on the leading columns, plus a range on the first column after them, are what reliably limit how much of the index gets scanned. So the order has to mirror how you filter: equality columns first, then the range or sort column.
-- Serves: WHERE tenant_id = $1 AND created_at >= $2 ORDER BY created_at DESC
CREATE INDEX idx_events_tenant_time
ON events (tenant_id, created_at DESC);
-- Equality columns first, then the range or sort column.
-- Reversed (created_at, tenant_id), the scan reads every
-- tenant's entries in the time range to find this one's.That’s the whole difference on a multi-tenant dashboard query. With (created_at, tenant_id), the index scan walks every tenant’s entries for the time window and discards most of them. Postgres 18’s skip scan doesn’t rescue it, because it only pays off when a leading column has few distinct values, and timestamps have many. With (tenant_id, created_at), it reads only the one tenant’s slice. Same columns, same data, same B-tree. The only difference is whether the index answers the question in the order the query asks it.
A B-tree stops paying off the moment the question changes from “which rows have this value” to “which rows contain this value”. Containment in JSONB, membership in arrays and word matching in text all leave B-tree territory. It also rarely helps on a low-cardinality column like an evenly split boolean: a query matching more than a few percent of the table won’t use the index anyway.
When does a GIN index pay off over a B-tree?
The moment you query inside a value rather than comparing the whole value. In most systems that means three workloads: JSONB containment, array membership and full-text search. A GIN index stores each key, element or word once, with a list of the rows that contain it, which is why it can answer “which rows contain this key” without checking every row.
-- JSONB containment
CREATE INDEX idx_orders_meta ON orders USING gin (metadata);
SELECT * FROM orders WHERE metadata @> '{"channel": "mobile"}';
-- Array membership
CREATE INDEX idx_posts_tags ON posts USING gin (tags);
SELECT * FROM posts WHERE tags @> ARRAY['postgres'];
-- Full-text search
CREATE INDEX idx_docs_fts ON docs USING gin (to_tsvector('english', body));The catch mirrors the benefit. Because one row can add many keys, the docs warn that GIN insertion can be slow, and build time is very sensitive to maintenance_work_mem. GIN partly hides this with a pending list that batches new entries, but the insert that pushes the list past gin_pending_list_limit triggers an immediate cleanup and runs much slower than the rest, unless autovacuum keeps the list short. On a write-heavy table, an eager GIN index is a tax on every insert to speed up a query you might run occasionally. Is that trade still positive for your workload? Sometimes, yes. It deserves the question.
There’s a planning subtlety too: GIN answers containment brilliantly but doesn’t help you rank or sort results. For full-text search at modest scale that’s fine, and built-in Postgres search covers a lot of ground. Ranking millions of documents by relevance under load is a different job, and retrieval quality and hybrid search get their own treatment in why your RAG system is actually a search problem.
Is a BRIN index worth using?
Yes, for one specific shape of data, and there it’s almost embarrassingly cheap. A BRIN index doesn’t store an entry per row. It stores a summary per block range, the minimum and maximum value in each chunk of physical pages, so the index stays tiny: by default one summary covers 128 table pages, where a B-tree holds an entry for every row.
For a query like “give me last week’s rows” on a table where rows were inserted in time order, that summary lets Postgres skip most of the table:
-- Append-only events table, rows arrive in time order
CREATE INDEX idx_events_created_brin
ON events USING brin (created_at);
-- The index stores min/max per block range, so a range query
-- skips every block whose summary can't contain matching rows.The word doing all the work is physical. BRIN only helps when the physical order of rows on disk correlates with the indexed column. Append-only logs, events, metrics and audit trails have that property naturally: time only moves forward, and rows land in arrival order. Once a table sees heavy updates and deletes, vacuumed space gets reused, new rows land in old pages, correlation decays, and every block range’s min/max widens until the index can’t exclude anything.
A useful mental model: a B-tree indexes a column, while BRIN indexes the table’s life story. If the story is “rows arrive in order and stay put”, BRIN is close to free performance. If the story involves churn, BRIN quietly stops helping without ever raising an error, which is worse than failing loudly. Check the column’s correlation in pg_stats before you trust it:
-- How closely does physical row order track created_at?
SELECT attname, correlation
FROM pg_stats
WHERE schemaname = 'public' AND tablename = 'events' AND attname = 'created_at';correlation runs from -1 to +1. Near 1 or -1, physical order tracks the column, so block ranges stay narrow and BRIN can skip the ones that can’t match; near 0, it has little to skip. The figure comes from the last ANALYZE, which samples the table, so refresh it after big changes.
BRIN stops paying off when that correlation breaks: update-heavy tables, out-of-order backfills, or columns unrelated to insert order. It’s also the wrong tool for point lookups. It narrows the search to block ranges rather than finding individual rows, so WHERE id = 42 still wants a B-tree. For genuinely large time-series workloads, BRIN is also the on-ramp to a bigger conversation about partitioning and time-series storage.
What do partial and expression indexes buy you?
A smaller problem. A partial index covers only the rows matching a predicate, and an expression index covers a computed shape of a column instead of the raw value. Both say the same thing: my queries don’t touch the whole table, so my index shouldn’t either. The result is smaller, faster to scan and cheaper to maintain.
The classic partial-index case is a status column where the interesting rows are a small minority. If 98 percent of jobs are done and every query polls for pending ones, indexing every status mostly indexes rows nobody asks about:
-- Only pending jobs are ever polled
CREATE INDEX idx_jobs_pending
ON jobs (created_at)
WHERE status = 'pending';
-- Case-insensitive login lookups
CREATE INDEX idx_users_email_lower
ON users (lower(email));
SELECT * FROM users WHERE lower(email) = lower($1);The part that surprises people: a partial index skips index writes entirely for rows that don’t match the predicate. On a queue table where completed jobs vastly outnumber pending ones, that’s a real write saving, not just a storage one.
Expression indexes apply the same logic in a different direction. If every query wraps the column in lower(), a plain index on email never gets used, because the planner sees lower(email), not email. Index the expression your query actually contains, and the planner can match the two. The rule for both features is exact matching: the predicate or expression in the index has to line up with what the query says, closely enough that the planner can prove it.
Partial indexes stop paying off when the predicate no longer mirrors real query shapes, or when you’ve minted a bespoke partial index for every screen in the app. A dozen overlapping partials on one table is index sprawl wearing a clever disguise, and the planner still has to pick between them. If you can’t name the exact recurring query a partial index serves, it shouldn’t exist.
Can a covering index really let Postgres skip the table?
Yes, and when it works it’s the closest thing indexing has to a free lunch, with two honest conditions attached. Normally an index scan finds matching entries, then visits the heap to fetch the remaining columns. If the index itself contains every column the query needs, Postgres can run an index-only scan and never touch the table.
-- Query: SELECT status, total FROM orders WHERE customer_id = $1
CREATE INDEX idx_orders_customer_covering
ON orders (customer_id) INCLUDE (status, total);INCLUDE adds payload columns to the index leaves without making them part of the search key, so the index stays efficient to search while carrying the answer with it. For hot, narrow lookups, the ones that run thousands of times a minute and fetch two columns, this can remove the heap visits from the query.
Condition one: visibility. Postgres can only skip the heap for pages it knows are all-visible, and that information is maintained by vacuum. On a table with heavy churn, many pages lose that status between vacuums, and your “index-only” scan quietly does heap fetches anyway.
Condition two: weight. Every INCLUDE column makes the index physically bigger, and a bigger index means more WAL, slower writes, and less of it fitting in cache. Stuffing six columns into INCLUDE to chase index-only scans on a wide query usually costs more than it saves. Covering indexes are for narrow, frequent reads, not for smuggling the whole table into the index.
Covering indexes stop paying off on update-heavy tables that never keep a clean visibility map, and on queries wide enough that the INCLUDE payload bloats the index. If the query needs half the row anyway, let it visit the heap. That’s what the heap is for.
What does every index cost you on writes?
Every index on a table adds work to inserts, to updates that can’t use HOT, and to the vacuuming that cleans up after deletes and updates, and the bill compounds in ways that never show up in query benchmarks. Each new row goes into each index that covers it, and an update that changes an indexed column also defeats Postgres’s HOT optimization.
HOT is the subtle one. When an update changes no indexed column and the new row version fits on the same heap page, HOT keeps it there without adding any index entries. Index a frequently updated column, and every update to that column misses HOT and has to add entries to the table’s other indexes as well, not just the new one.
Then there’s the operational tail: more WAL to ship and replay on recovery, bigger physical backups, longer vacuums, more index bloat to monitor. None of it is dramatic alone. Together, it’s why an over-indexed hot table feels sluggish in ways nobody can pin on a single query.
The good news is that Postgres tells you exactly which indexes are earning their keep:
SELECT schemaname, relname, indexrelname,
idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
ORDER BY idx_scan ASC, pg_relation_size(indexrelid) DESC;
-- idx_scan = 0 since the last stats reset means no query on
-- this server has scanned it. Replicas keep their own counts.
-- Confirm the stats window covers real traffic before dropping.Run it quarterly. Anything with zero scans over a genuine traffic window, and no constraint duty, is a candidate to drop. What does an unused index actually give you? Slower writes, bigger backups, and a false sense of preparedness. The audit is also one of the quieter levers on your infrastructure bill, because index storage and the extra write I/O can both show up on a managed database’s invoice. That cost side is the subject of database choices that quietly kill your AWS bill.
How do you choose the right index type?
Ask four questions, in order: what the query is actually asking, which rows it asks about, what the table’s write profile is, and whether the index got used. The point isn’t ceremony. Each question eliminates most of the remaining options, and together they settle most indexing decisions.
- What is the query actually asking? Whole-value equality, range or sort points at B-tree. Looking inside a value, such as JSONB keys, array elements or words in text, points at GIN. A range over time-ordered, append-only data points at BRIN. Write the query first, then read the operator it needs. The operator names the index type.
- Which rows does it ask about? If the answer is “a small, describable slice”, a partial index beats indexing the world. If the query wraps the column in a function, the expression is what needs indexing, not the column.
- What’s the write profile of this table? A read-mostly table tolerates generous indexing. A hot write path makes every index type more expensive, and makes GIN and wide covering indexes specifically questionable. If the table is both write-hot and query-hot, that tension is the design problem, and no index type dissolves it.
- Did it actually get used? Confirm with
EXPLAIN ANALYZEthe day you add it, then checkpg_stat_user_indexesafter a week of real traffic. An index the planner ignores is indistinguishable from one you never built, except that you’re paying for it.
The same answers, one row per tool:
| Index type | Pays off when | Stops paying off when |
|---|---|---|
| B-tree | Equality, range or sort on whole values | Containment, arrays, full-text; low-cardinality columns |
| GIN | Looking inside values: JSONB, arrays, full-text | Writes are the constraint; ranking by relevance under load |
| BRIN | Ranges on append-only, in-order tables | Churn breaks physical correlation; point lookups |
| Partial and expression | Queries touch a small slice or a computed shape | The predicate drifts from real queries; one partial per screen |
Covering (INCLUDE) | Hot, narrow reads that can skip the heap | A stale visibility map; a wide payload |
Answer those four honestly and what’s left are details. Skip them and you’re back to the coin flip from the war room. The same decision-first approach works one level up, for the service itself: see when to use each AWS database service.
What does a sensible indexing default look like?
The practical default is an old one, and it’s still correct: a small number of B-tree indexes shaped by your actual query patterns, with composite column order matching how you filter. Then GIN when queries look inside values, BRIN for in-order append-only data, partial indexes for a slice of rows, and INCLUDE for hot, narrow reads.
Five tools, each with one clear job.
The failure mode isn’t picking the wrong type once. It’s accumulation: indexes added under incident pressure, never matched to a named query, never audited, until the table pays double on every write to maintain structures nothing reads. That schema doesn’t look broken in any single EXPLAIN. It just gets slower everywhere, gradually and expensively.
An index pays off when it matches the question your query asks. Everything else is rent. If the slow query turns out to be a capacity problem rather than a plan problem, read replicas vs caching vs both is the next decision. The rest of the Databases section covers the ground around it.
Key takeaways
- B-tree is the right default for equality, range and sort queries. It's the wrong tool for containment, arrays and full-text, no matter how many of them you stack.
- GIN pays off the moment you query inside a value: JSONB containment, array membership, text search. The price is slower inserts, and builds that need generous maintenance_work_mem.
- BRIN is tiny, so scanning it adds little overhead, but it only works when physical row order correlates with the indexed column, which usually means append-only, time-ordered data.
- Partial and expression indexes shrink the problem instead of the query: index only the rows and the shapes your queries actually touch.
- Every index taxes writes to its table. If pg_stat_user_indexes shows zero scans, the index isn't an asset, it's rent.

Questions people ask
What is the default index type in PostgreSQL?
B-tree. It's what you get whenever you run CREATE INDEX without naming a method, and it handles equality, range comparisons, sorting and uniqueness, which fits the most common situations. Primary keys and unique constraints are backed by B-tree indexes automatically, since only B-tree supports unique indexes, so almost every schema already relies on them, whether anyone chose them or not.
When should I use GIN instead of B-tree in Postgres?
When queries look inside composite values rather than comparing whole values: JSONB containment, array membership and full-text search. GIN keeps an entry for each key, element or word, with the rows that contain it, so it answers containment queries a B-tree can't. The trade-off is slower inserts and builds that need generous maintenance_work_mem, so apply it only where those queries actually run.
Do indexes slow down writes in PostgreSQL?
Yes. Inserts, and updates that can't be done as HOT updates, have to add entries to the table's indexes, which costs I/O and WAL. Indexing a frequently updated column stops updates to that column from using HOT, and vacuum has to clean dead entries out of the indexes. Read speedups usually justify the cost, but only for indexes queries use.
What is a partial index in PostgreSQL?
An index that covers only the rows matching a WHERE predicate defined when the index is created, such as jobs with status pending. It's smaller, cheaper to maintain, and skips index writes entirely for rows that don't match. The planner uses it only when it can prove the query's condition implies the predicate, so mirror real query shapes exactly.
How do I find unused indexes in Postgres?
Query pg_stat_user_indexes for indexes with idx_scan at or near zero over a window of real production traffic, sorted by size. Each server keeps its own counts, so check replicas too. Before dropping anything, confirm the index isn't enforcing a unique constraint and isn't needed by periodic jobs, such as month-end reports, that run outside your stats window.
Get the next article by email
One email when a new deep-dive is out: databases, cloud and AI, with the code. Unsubscribe in one click.
Email signups open soon. Until then, new articles are announced on Instagram.
