On this page
Indexes & EXPLAIN ANALYZE
Prev: JSONB, Arrays & Advanced Types | Up: postgresql | Next: Security, Roles & Row-Level Security
Rel: Indexing & Storage Engines, SQL Query Execution Lifecycle
Ref: PostgreSQL — Index Types
Tags: #public #databases #postgresql #indexing #performance
Contents
Choosing a PostgreSQL Index Type
| Index Type | Best For |
|---|---|
| B-Tree (default) | Equality (=), ranges (<, BETWEEN), ORDER BY, prefix LIKE 'abc%' |
| GIN | JSONB (@>), TEXT[] arrays, tsvector full-text search |
| GiST | Ranges (&&), PostGIS geometry, trigram similarity (pg_trgm) |
| BRIN | Huge append-only tables correlated with physical order (timestamps/logs) |
| Hash | Pure equality (=) on large values where ordering isn't needed |
Build indexes without blocking production writes using CREATE INDEX CONCURRENTLY ....
Reading EXPLAIN (ANALYZE, BUFFERS)
Always include BUFFERS to see actual page hits vs. disk reads (note: ANALYZE executes the query; wrap writes in BEGIN; EXPLAIN ANALYZE ...; ROLLBACK;):
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total_cents
FROM orders
WHERE user_id = 42 AND status = 'paid'
ORDER BY created_at DESC
LIMIT 20;
Watch for: large mismatches between estimated rows and actual rows (stale stats -> run ANALYZE), unexpected Seq Scan on large tables, Rows Removed by Filter, and Sort Method: external merge Disk (insufficient work_mem).
Linked from
- tuts/databases/design_patterns/indexing_and_storage_engines
- tuts/databases/design_patterns/scaling_partitioning_and_sharding
- tuts/databases/postgresql
- tuts/databases/postgresql/indexes_and_explain_analyze
- tuts/databases/postgresql/jsonb_arrays_and_advanced_types
- tuts/databases/postgresql/security_roles_and_rls
- tuts/databases/sql/aggregations_ctes_and_windows
- tuts/databases/sql/query_execution_lifecycle
Related notes
- tuts/databases/design_patterns/indexing_and_storage_engines Linked here; links to this page; shared tags: #databases, #indexing
- tuts/databases/postgresql Linked here; links to this page; shared tags: #databases, #postgresql
- tuts/databases/postgresql/jsonb_arrays_and_advanced_types Linked here; links to this page; shared tags: #databases, #postgresql
- tuts/databases/postgresql/security_roles_and_rls Linked here; links to this page; shared tags: #databases, #postgresql
- tuts/databases/sql/query_execution_lifecycle Linked here; links to this page; shared tags: #databases
- tuts/databases/design_patterns/scaling_partitioning_and_sharding links to this page; shared tags: #databases
- tuts/databases/sql/aggregations_ctes_and_windows links to this page; shared tags: #databases
- tuts/databases/mongodb/indexes_replica_sets_and_transactions shared tags: #databases, #indexing
- tuts/databases/postgresql/mvcc_vacuum_and_wal shared tags: #databases, #postgresql
- tuts/databases/sqlite3/wal_mode_and_pragmas shared tags: #databases, #performance