Database index
An extra data structure a database keeps next to a table so it can find matching rows without reading the whole table.
A database index works like the index at the back of a book: a sorted or hashed copy of one or more columns with pointers to the rows. Without one, the database scans every row; with the right one, it jumps to the few that match. “The app got slow when we hit more customers” is very often a missing index.
Indexes are not free. Every insert and update has to change each index too, they take disk and memory, and the planner uses only those that fit the query. Postgres alone offers several index types, each built on a different data structure, and extensions add more, such as HNSW from pgvector for vector search.
The table below maps the common kinds to the structure behind them. To check what a query really does, run it with EXPLAIN ANALYZE and look for sequential scans on large tables.
| Index (Postgres name) | Structure | Good for |
|---|---|---|
| B-tree (default) | B-tree | Equality, ranges, sorting, prefix search |
| Hash | Hash table | Equality only |
| GIN | Inverted index | Full-text search, JSON keys, arrays, trigrams |
| GiST (PostGIS) | R-tree | Maps, nearest location, overlapping ranges |
| HNSW (pgvector) | HNSW | Nearest vectors for semantic search and RAG |
| BRIN | Block summaries | Huge tables naturally ordered by time |
Sources
- PostgreSQL: Index Types postgresql.org
- GitHub: pgvector/pgvector github.com
Related terms
- B-tree: A sorted, wide and shallow tree that stores keys in disk-sized pages; the default index in most relational databases.
- Hash table: A structure that finds a value by its key in about constant time by hashing the key into a slot; fast lookups, no order.
- Inverted index: A map from each word to the list of documents that contain it; the structure behind keyword search engines and BM25.
- R-tree (spatial index): A tree that groups nearby shapes into nested bounding boxes, so maps can quickly answer “what is near here” and “what is inside this area”.
- HNSW (hierarchical navigable small world): A layered graph index that finds approximately nearest vectors fast; the default index in most vector databases, trading a little recall for speed.
- Big O notation: Shorthand for how the work an algorithm does grows as its input grows, such as O(1), O(log n), O(n) or O(n²).
- LSM tree (log-structured merge tree): A storage design that buffers writes in memory and flushes them as sorted files merged in the background; fast writes, more work on reads.
- Columnar storage (Parquet, ClickHouse): Storing a table column by column instead of row by row, so analytics that read a few columns over many rows are fast and compress well.
