Index Types: B-tree vs Hash vs GIN vs GiST vs BRIN

2026-12-04来源 dev.toEnglish

CREATE INDEX without anything else gives you a B-tree, and most of the time that is the right call. But PostgreSQL ships several other index types, each built for a different shape of data and a different kind of question. Picking the right one can turn a full table scan into a fast lookup, or an index the size of the table into one that fits in a few pages.

This cheat sheet compares the five you are most likely to meet: B-tree, Hash, GIN, GiST and BRIN. The names are PostgreSQL's, but the ideas exist in other databases too.

The five at a glance

B-tree is a balanced, sorted tree. It answers equality (=), ranges (<, >, BETWEEN), sorting (ORDER BY), IS NULL, and prefix matches like LIKE 'abc%' (with the C collation or a text_pattern_ops index). It is the only type here that can enforce UNIQUE and back a primary key. It supports multi-column indexes and index-only scans.

Hash stores a hash of the value. It only answers =. In exchange, its entries can be smaller than a B-tree's for long values such as long strings. Since PostgreSQL 10 hash indexes are WAL-logged and crash-safe, so the old warning against them no longer applies. Still, a B-tree also handles = well, so hash indexes are a niche choice.

GIN (Generalized Inverted Index) maps each element to the rows that contain it, like the index at the back of a book. It is built for values that contain many items: arrays, jsonb documents, full-text tsvectors, and trigram search with the pg_trgm extension. It answers "contains" questions: @>, ?, &&, @@. Lookups are fast; inserts and updates are slower, because one row can add many index entries.

GiST (Generalized Search Tree) is a framework for tree indexes over data that does not sort on a single line: geometric shapes, PostGIS geometries, ranges, network addresses. It answers overlap, containment and distance questions, supports nearest-neighbor search with ORDER BY location <-> point, and backs exclusion constraints such as "no two bookings for the same room overlap".

BRIN (Block Range Index) does not index rows at all. It stores a summary, typically the min and max value, for each range of table blocks. When the data is physically in order, such as an append-only table with created_at, a BRIN index is tiny and lets the planner skip most of the table. When the data is scattered, it helps very little.

Side by side

B-tree Hash GIN GiST BRIN
Best for Scalars, most columns Equality on long values Arrays, jsonb, full text Geometry, ranges, nearest Huge ordered tables
Operators = < > BETWEEN sort = only @> ? && @@ && @> <-> = < > on ranges of blocks
Size Medium Small to medium Large Medium Tiny
Write cost Low Low High Medium Very low
Unique / PK Yes No No No (exclusion only) No
Sorted output Yes No No Distance order only No

Examples

-- B-tree: the default CREATE INDEX ON orders (customer_id, created_at); -- Hash: equality only CREATE INDEX ON sessions USING hash (token); -- GIN: query inside jsonb and arrays CREATE INDEX ON products USING gin (attributes); SELECT * FROM products WHERE attributes @> '{"color": "red"}'; -- GiST: overlapping ranges, nearest neighbor CREATE INDEX ON bookings USING gist (during); -- BRIN: append-only log table CREATE INDEX ON events USING brin (created_at); 

Common mistakes

  • Using B-tree for jsonb containment. A B-tree on a jsonb column only helps whole-value equality. For @> you need GIN.
  • BRIN on unordered data. If rows arrive in random order of the indexed column, every block range covers almost everything, and the index skips nothing.
  • GIN on a write-heavy table without measuring. GIN has a pending list (fastupdate) to soften the write cost, but large or frequent updates can still slow inserts. Measure before and after.
  • Expecting LIKE '%abc%' to use a B-tree. A leading wildcard cannot use a B-tree. A GIN or GiST index with pg_trgm can.
  • Indexing everything. Each index slows writes and takes space. Check pg_stat_user_indexes for indexes that are never used.
  • Not checking the plan. Run EXPLAIN ANALYZE to see whether the planner actually uses the index.

When to pick which

  • Pick B-tree by default: primary keys, foreign keys, equality and range filters, sorting, unique constraints.
  • Pick Hash only when a column is queried with = alone, the values are long, and you have measured a gain over B-tree.
  • Pick GIN when one value contains many searchable items: jsonb, arrays, full-text search, fuzzy text search with trigrams.
  • Pick GiST for spatial data, ranges and time periods, nearest-neighbor queries, and exclusion constraints.
  • Pick BRIN for very large tables where the column follows the physical order of the rows, such as timestamps on append-only logs, and where a small index matters more than precise lookups.

If in doubt, start with B-tree, look at the queries that are still slow, and match each one to the index type built for its operator.

Watch the animated version: https://youtu.be/bdvHE4Hfuwc

Originally published at abdeldjalilchougui.biz.

原文:https://www.a8q9.cn/en/article/index-types-b-tree-vs-hash-vs-gin-vs-gist-vs-brin-e16c88.html

相关文章