skip to content

GIN, GiST & BRIN

GIN indexes jsonb, arrays and text; GiST and SP-GiST index ranges, geometry and nearest-neighbour; BRIN suits huge ordered tables; hash does equality. Interviewers ask which fits a workload.

part ofPostgreSQLread it →
on this pageshow

explore

questions

6

In PostgreSQL, beyond the default B-tree, which index access methods ship in core, and what kind of query is each one built for?

level: juniorimportance: must knowfreq 74%

answer

  1. USING picks the method
  2. many keys inside one value
  3. overlap, containment, nearest first
  4. one summary per block range
  5. equality and nothing else

basics

~10 s

Core PostgreSQL adds hash (equality only), GIN (values holding many keys: arrays, jsonb, tsvector), GiST and SP-GiST (geometry, ranges and nearest-neighbour ordering with <->) and BRIN (tiny per-block-range summaries for huge, physically ordered tables).

solid answer

~40 s

`CREATE INDEX ... USING method` picks one of five non-default methods, and the column's **operator class** decides which operators the index can serve. `gin` is an inverted index for values that contain many keys: `tags @> ARRAY['coastal']` on a `text[]`, jsonb containment, `tsvector` documents and trigram search through `pg_trgm`. `gist` is a balanced tree of possibly overlapping keys for geometry, ranges and `inet`, and it can return rows nearest-first for `ORDER BY location <-> point '(10,20)' LIMIT 5`. `spgist` builds non-balanced space-partitioning trees (quad-tree, k-d tree, radix tree) for points and text. `brin` keeps a min/max summary per block range and suits a billion-row append-only `readings` table filtered on `observed_at`. `hash` serves only `=` on one column, with no uniqueness and no index-only scans.

code

sql · 18 lines
sql
CREATE TABLE stations (
    station_id   integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    station_code text NOT NULL,
    name         text NOT NULL,
    tags         text[] NOT NULL DEFAULT '{}',
    location     point NOT NULL
);
CREATE INDEX stations_tags_gin      ON stations USING gin  (tags);
CREATE INDEX stations_location_gist ON stations USING gist (location);
CREATE INDEX stations_code_hash     ON stations USING hash (station_code);

CREATE TABLE readings (
    station_id    integer NOT NULL REFERENCES stations,
    observed_at   timestamptz NOT NULL,
    temperature_c numeric(5,2),
    payload       jsonb NOT NULL
);
CREATE INDEX readings_observed_brin ON readings USING brin (observed_at);

go deeper

for a junior

Know that a plain CREATE INDEX builds a B-tree and name the other methods with one workload each: GIN for arrays and jsonb, GiST for geometry and nearest-neighbour, BRIN for huge time-ordered tables.

for a middle

Explain that the operator class decides which operators an index can serve, and state the limits that bite: GIN and BRIN scan by bitmap only, hash serves only equality on one column, SP-GiST is single-column.

for a senior

Pick the method from the predicate and the physical layout of the data, and say what it costs: GIN write amplification, BRIN's dependence on insert order, GiST recheck work, and when a plain B-tree still wins.

for a principal

Treat index choice as a cost across a whole workload: write volume, storage and vacuum work against the number of query shapes one index must serve, and know when an extension's access method is the right owner instead of core.

## The method and the operator class When you write `CREATE INDEX ON stations (name)` with no `USING` clause, PostgreSQL builds a **B-tree**. Five other index **access methods** ship in core: `hash`, `gist`, `spgist`, `gin` and `brin`. In `psql`, `\dA` lists the access methods installed in a database and `\dAc gin` lists the operator classes GIN has for each data type. The method alone does not decide what an index can do. Every indexed column uses an **operator class**, which tells the method which operators it can accelerate for that data type. A GIN index on a `text[]` column uses `array_ops` and serves `&&`, `@>`, `<@` and `=` between arrays; a GIN index on `jsonb` uses `jsonb_ops` unless you name `jsonb_path_ops`. The planner considers an index only when the `WHERE` clause applies one of those operators directly to the indexed column or expression, or when `ORDER BY` uses one of the class's ordering operators. ## What each method is for | Method | Built for | Typical predicate | Notable limits | |---|---|---|---| | `btree` (default) | sortable scalars | `=`, `<`, `BETWEEN`, `ORDER BY` | covered by the B-tree leaf | | `hash` | equality on one column | `station_code = 'WS-0042'` | `=` only, single column, no `UNIQUE`, no index-only scan | | `gin` | values holding many keys | `tags @> ARRAY['coastal']` | bitmap scans only, no ordering, costly writes | | `gist` | overlapping shapes, ranges, nearest-neighbour | `ORDER BY location <-> point '(10,20)'` | many classes are lossy, so rows are rechecked | | `spgist` | non-overlapping partitions of space | points, text prefixes, `inet` | single column only | | `brin` | huge tables whose column follows physical order | `observed_at >= now() - interval '1 day'` | useless when values are scattered | ## GIN: many keys per row **GIN** (Generalized Inverted Index) stores each key extracted from a value once, with the set of rows containing it. That is why it fits a station's `tags text[]`, a reading's `payload jsonb`, a `tsvector` document, or the trigrams of a station name through the `pg_trgm` extension's `gin_trgm_ops`. It answers queries only through **bitmap index scans**, cannot return rows in order, and pays a high cost per insert, because one new row can add dozens of keys. Its `fastupdate` pending list exists to soften that cost. ## GiST and SP-GiST: shapes, ranges and nearest-first **GiST** (Generalized Search Tree) is a balanced tree whose internal entries cover their children, such as a bounding box around a group of points. Entries may overlap, which lets GiST index boxes, polygons, circles, range types and `inet` (through the non-default `inet_ops`). Operator classes that list an **ordering operator** such as `<->` let it return rows nearest-first. **SP-GiST** (space-partitioned GiST) builds non-balanced structures whose partitions do not overlap: quad-trees (`quad_point_ops`, the default for `point`), k-d trees (`kd_point_ops`) and radix trees (`text_ops`). Its point classes also support `<->`. Unlike GiST, it indexes only one column. ## BRIN: a tiny index for a huge table **BRIN** (Block Range Index) stores one small summary per range of table blocks, by default `pages_per_range = 128`. With the default `minmax` classes the summary is the minimum and maximum of the column in that range. A query skips every range whose summary cannot match and rechecks every row in the ranges it keeps, which only pays off when the column's values follow their physical position, as `observed_at` does in an append-only readings table. ## Hash: equality and nothing else A **hash** index stores just a 4-byte hash code per row, so it can be much smaller than a B-tree on long keys such as URLs or external station codes. It is fully crash-recoverable, but it serves only `=`, covers a single column, cannot enforce `UNIQUE`, cannot feed an index-only scan, and every match is rechecked against the heap. When the column is also sorted, range-filtered or unique, a B-tree is the better choice. ## Choosing in an interview Start from the predicate, not the method: 1. Does the query ask whether a value **contains** keys (array elements, jsonb paths, words, trigrams)? Use GIN. 2. Does it ask about **overlap or distance** between shapes, ranges or points? Use GiST, or SP-GiST for points and prefixes. 3. Is the table **huge and append-ordered** on the filtered column? Try BRIN. 4. Is it only `=` on a long key that is never sorted or unique? Consider hash. 5. Otherwise stay on the B-tree. Vector similarity indexes such as HNSW and IVFFlat come from the pgvector extension and are a separate subject, as is contrib's `bloom` access method.

  • Why does WHERE 'coastal' = ANY(tags) ignore a GIN index on tags, and what do you write instead?
    GIN's `array_ops` class indexes the array operators `&&`, `@>`, `<@` and `=` between two arrays. `'coastal' = ANY(tags)` is a scalar equality repeated over the elements, so it is not one of those operators applied to the indexed column. Rewrite it as `tags @> ARRAY['coastal']`, which returns the same rows and can use the index through a bitmap scan.
  • Can a GIN or BRIN index satisfy ORDER BY observed_at without a sort?
    No. Both methods only produce bitmap scans, which hand back matching pages in physical order rather than key order, so PostgreSQL adds a Sort above the bitmap heap scan or picks a B-tree that can return rows in order. GiST and SP-GiST can order rows only by distance, through an ordering operator such as `<->`.

  • A hash index is not crash-safe, so it must be rebuilt after a crash.
  • A GIN index on a column can serve ORDER BY on that column.
  • BRIN helps any large table, whatever order the rows were written in.
  • SP-GiST is just GiST with better defaults and multicolumn support.
  • Writing USING gin is enough; the operator class never changes what is indexed.
open as a page

In PostgreSQL, how do the GIN operator classes jsonb_ops and jsonb_path_ops differ, and when would you choose jsonb_path_ops?

level: middleimportance: should knowfreq 52%

basics

~20 s

jsonb_ops, the default, indexes every key and value separately and serves ?, ?|, ?&, @>, @? and @@. jsonb_path_ops stores one hash per value including its key path, serves only @>, @? and @@, and is usually smaller and more selective.

open as a page

On a PostgreSQL append-only readings table of billions of rows, when does a BRIN index on observed_at beat a B-tree, and what does pages_per_range trade?

level: seniorimportance: should knowfreq 47%

basics

~20 s

BRIN wins when observed_at rises with physical position: each block range's min/max summary excludes most of the table at a tiny index size. pages_per_range (default 128 blocks) trades index size against heap pages rechecked per matching range.

open as a page

In PostgreSQL, a GIN index on readings.payload keeps most inserts fast, but a few stall for seconds; what is the GIN pending list, and how do you tame it?

level: seniorimportance: should knowfreq 36%

basics

~20 s

With fastupdate on, the default, GIN appends new entries to an unsorted pending list and merges them in bulk later. The insert that pushes the list past gin_pending_list_limit (4MB) does the whole merge itself and stalls; searches also scan the list.

open as a page

In PostgreSQL, how does a GiST or SP-GiST index answer ORDER BY location <-> point '(10,20)' LIMIT 3, and how do those two methods differ?

level: middleimportance: nice to knowfreq 28%

basics

~20 s

GiST and SP-GiST both list <-> as an ordering operator for points, so an index scan returns rows nearest-first and stops at the LIMIT. GiST is a balanced, multicolumn tree of overlapping bounding keys; SP-GiST builds single-column, non-overlapping quad-trees, k-d trees or tries.

open as a page