Choosing the right Postgres indexes
Postgres indexes pay off for frequently run queries that discard most rows they read, need results in a specific order, or must enforce uniqueness. In a 500k-row example, adding a B-tree index cuts a lookup from 215ms to 0.05ms. Put the most frequently filtered columns first in composite indexes, prefer reusable indexes over narrowly tailored ones, and use partial indexes (e.g. WHERE archived_at IS NULL) to keep them small. Missing indexes can be spotted with a Grafana panel on pg_stat_user_tables_seq_tup_read and confirmed with EXPLAIN ANALYZE.
Related posts
- If I have read-only tables in Postgres, should I index them heavily?
Neon mediumAdept
Even when writes are off the table, heavily indexing read-only Postgres tables only pays off under certain conditions: table size, query complexity, data cardinality and resource constraints. Benchmarks show no gain from an index on a 10k-row table, and a simple low-selectivity equality query on 10M rows was actually slower with an index (0.0078s vs 0.0026s). A multi-condition search with a range filter, ORDER BY and LIMIT dropped from 20.8s to 3.4s with indexing. The recommendation is to index columns used in WHERE, JOIN, ORDER BY and GROUP BY for critical queries, favor high-cardinality orderable types over booleans, and account for the disk, memory and CPU cost of extra indexes.
- The side quest that freed 10% of our database
incident.io mediumAdeptA single lateral-join query answering "who's on call for this rotation layer right now" consumed 34% of incident.io's Postgres replica CPU. It was using a GiST exclusion-constraint index that lacked organisation_id and start_at, so every lookup read a layer's full history. Adding a five-column btree index did nothing on its own, because the planner assumed the four ID columns were independent and kept choosing the GiST index. Rewriting the predicate as a row-value comparison with a matching ORDER BY, which only btree indexes can serve, forced the new index and cut per-call time from 44ms to 0.26ms, buffers by 115x and CPU share to 0.3%.
- Fix a top cause of slow queries in PostgreSQL (no slow query log needed)
Render mediumAdept
PostgreSQL automatically indexes primary keys and UNIQUE columns but not the referencing column of a foreign key, so lookups on that side and ON DELETE CASCADE / SET NULL triggers fall back to full table scans. In a simulated blog schema with 13 million comments, deleting a single user took 19 seconds, almost all of it in foreign-key triggers. Adding non-unique B-tree indexes on articles.author_id, comments.author_id and comments.article_id cut the delete to 342 ms, a 55x speedup, with the comments-by-article trigger dropping from 18 s to 26 ms. The rule of thumb is to index foreign key columns in referencing tables, and it is mandatory when ON DELETE propagation is defined.
- PostgreSQL Stories: From slow query to fast—via stats
Render mediumAdept
A simple LIMIT 1 join between a ~100k-row postgres_dbs table and a ~90M-row events table ran for hours. The cause was a merge join that scanned ~79M non-matching events sorted ahead of the 'dpg-' serviceId prefix. Adding manual lower and upper bounds on the indexed JSON expression brought the query down to milliseconds, but the real fault was that PostgreSQL only kept statistics on whole JSON objects, not on data->>'serviceId'. Running CREATE STATISTICS on that expression gave the planner accurate distributions, and the original query then finished in under a millisecond without rewrites.
- Postgres Support Recap: Investigating Postgres Query Performance
Neon mediumAdept
Three starting points for diagnosing slow Postgres queries: use pg_stat_statements to find long-running queries by mean execution time and then EXPLAIN ANALYZE them, check the cache hit ratio (in Neon via the neon_stat_file_cache view, since Neon extends shared buffers with a local file cache), and look for table and index bloat caused by MVCC dead tuples. A hit ratio below 99% suggests the working set doesn't fit in memory, which calls for more shared_buffers or a larger Neon compute. Bloat is reduced with VACUUM, VACUUM FULL or REINDEX, all of which take locks. PgHero, run via Docker, gives a free dashboard alternative.