B-Tree vs Hash vs GIN vs GiST: Choosing PostgreSQL Index Types
Pick the right PostgreSQL index type for your queries. Compare B-Tree, Hash, GIN, GiST, and BRIN for JSONB, full-text search, and time-series data.
When software engineers create database indexes in PostgreSQL using the standard CREATE INDEX idx_name ON table (column); syntax, PostgreSQL creates a B-Tree index by default. B-Tree indexes excel at scalar comparisons and ranges, but they cannot answer operators such as JSONB containment, array overlap, full-text matching, or geometric distance, so queries on those types fall back to sequential scans.
PostgreSQL provides six distinct index access methods: B-Tree, Hash, GIN, GiST, SP-GiST, and BRIN. Matching the index type to the operators your queries use can turn a full table scan into a fast index lookup.
Architectural Deep Dive: PostgreSQL Index Engines
Different data structures support distinct mathematical operators:
- B-Tree (Balanced Tree): Self-balancing tree structure optimized for ordered, scalar data. Supports
<,<=,=,>=,>, andBETWEENoperators, as well asORDER BYsorting without explicit memory sorts. - Hash: Stores a 32-bit hash value of the indexed key. Prior to PostgreSQL 10, Hash indexes were not Write-Ahead Logged (WAL-logged) and unsafe for production; since PostgreSQL 10 they are crash-safe and replicated. Because they store only a 32-bit hash per entry, they can be smaller than a B-Tree for long keys, but they support equality lookups only.
- GIN (Generalized Inverted Index): An inverted index where an entry contains a single element/key pointing to a sorted list of rows that contain that key. Ideal for multi-value types: JSONB, PostgreSQL arrays (
TEXT[]), andtsvectorfull-text search. - GiST (Generalized Search Tree): A balanced, tree-structured access method that acts as a base template. Used for geometric coordinates (PostGIS), IP address network ranges (
inet), and range types (daterange,tsrange). - BRIN (Block Range Index): Stores physical page ranges (for example, min and max values for every 128 disk pages). For naturally sequential, append-only timestamp tables, BRIN can be orders of magnitude smaller than a B-Tree.
Feature and Operator Support Comparison Matrix
| Index Type | Supported Data Types | Primary Target Operators | Index Storage Size | Build / Write Overhead |
|---|---|---|---|---|
| B-Tree | Integers, Strings, Dates | <, <=, =, >=, >, IS NULL |
Moderate to Large | Moderate |
| Hash | Long strings, UUIDs, Varchars | = strictly |
Moderate (often smaller than B-Tree for long keys) | Low |
| GIN | JSONB, Arrays, tsvector |
@>, ?, ?\|, ?&, @@ |
Large (Inverted keys) | High (mitigated by the pending list) |
| GiST | PostGIS geometry, tsrange |
&& (Overlap), @> (Contains), <-> (Distance) |
Moderate | High |
| BRIN | Timestamps, Auto-increment IDs (physically ordered) | <, <=, =, >=, >, BETWEEN |
Tiny (typically a small fraction of a B-Tree) | Extremely Low |
Implementation Examples in PostgreSQL
1. Accelerating JSONB Document Searches with GIN
When querying nested properties inside unstructured JSONB columns:
-- Create GIN index using jsonb_path_ops for optimal containment queries
CREATE INDEX idx_audit_log_payload ON audit_logs USING GIN (payload jsonb_path_ops);
-- High-speed index lookup using the @> containment operator
SELECT * FROM audit_logs
WHERE payload @> '{"event": "login", "status": "failed"}';
2. Slashing Storage on Multi-Gigabyte Time-Series Logs with BRIN
For an immutable, append-only events table where rows are inserted chronologically:
-- BRIN index indexing 128 disk blocks (1 MB) per summary range
CREATE INDEX idx_events_created_at_brin ON event_stream USING BRIN (created_at);
-- Query execution scans only physical disk ranges containing the target dates
SELECT COUNT(*) FROM event_stream
WHERE created_at BETWEEN '2026-11-01' AND '2026-11-07';
On large append-only tables, a B-Tree on the timestamp can take gigabytes, while a BRIN index on the same column often takes only megabytes. BRIN works well only when the column's values follow the physical row order: it skips block ranges whose min/max cannot match, then rechecks rows in the remaining ranges. Measure on your own data with pg_relation_size() and EXPLAIN (ANALYZE, BUFFERS) before switching.
Pro-Tip: Covering Indexes with the
INCLUDEClause When queries filter on column A but select column B (SELECT email FROM users WHERE id = 100), developers often create composite indexes on(id, email). In PostgreSQL 11+, useCREATE INDEX idx_users_id_covering ON users (id) INCLUDE (email);. This creates a smaller B-Tree keyed strictly onidwhile storing
When drafting and optimizing complex database schema definitions or index migration scripts, format and validate your SQL syntax using our SQL Formatter. If you need to compare query plan structures or schema DDL outputs between migration runs, inspect your schema differences with our Object Comparison.
Frequently Asked Questions (FAQ)
What is the difference between jsonb_ops and jsonb_path_ops in GIN?
jsonb_ops (the default) creates separate index items for each key and value, which allows key-exists queries such as payload ? 'key'. jsonb_path_ops creates one item per value, hashed together with the keys leading to it. It does not support the key-exists operators, only @>, @?, and @@, but according to the PostgreSQL documentation it is usually much smaller than a jsonb_ops index on the same data and gives more specific searches.
Why does a GIN index slow down database write operations?
Every time a row with a JSONB object containing 20 keys is inserted, GIN must update 20 distinct inverted key lists. PostgreSQL mitigates this with the fast-update mechanism (fastupdate = on, the default): new entries go to an unsorted pending list, which is merged into the main index when the table is vacuumed or autoanalyzed, when gin_clean_pending_list() is called, or when the list exceeds gin_pending_list_limit. The trade-off is that searches must also scan the pending list.
When should Hash indexes be preferred over B-Tree?
Hash indexes are useful when indexing extremely long text strings (such as full URLs or 500-character description fields) where queries only perform exact equality matching (WHERE url = '...'). The Hash index stores fixed 4-byte hash codes rather than the full values, which can make it smaller. It also accepts values too large for a B-Tree entry (roughly one third of a page), though in most cases a B-Tree remains the safer default.