Relational databases: collection tree

Relational databases

PostgreSQL index methods and operators

Deep diveAbout 14 minutes AI-generated

An index can store an ordered value, the keys inside a value, or a summary covering many values. Those choices determine which questions it can answer. A customer ID has an order that a B-tree can search. “Contains the tag gift” asks about an element inside an array. “Overlaps this reservation” asks about two intervals. “Falls on this day” can sometimes exclude whole ranges of table pages.

PostgreSQL supplies six built-in access methods: B-tree, hash, GIN, GiST, SP-GiST and BRIN. The method supplies the structure. An operator class connects a particular type and its operators to that structure. Choosing both starts with what the query means, then asks what information the index must retain to help answer it.

Indexes and access paths develops composite keys, selectivity and ordered limits. Inside PostgreSQL follows an index entry to a visible heap tuple. Here we keep those ideas and change the information in the index. Small drawings are models; the plan observations come from an owned disposable PostgreSQL 18.6 server.

Access methods and operator classes

USING selects the method. The name after an indexed column, when present, selects its operator class. Leaving it out chooses the default class for that type and method:

CREATE INDEX products_name_prefix
ON products USING btree (name text_pattern_ops);

CREATE INDEX product_tags_gin
ON product_tags USING gin (tags array_ops);

The first definition keeps a B-tree but changes how text is compared. The second indexes the component values of a text[] column. product_tags is a separate illustrative catalogue projection; P7 retains its established gift and ceramic tags. Neither definition changes the meaning of the SQL operator.

An ordered key can narrow a range and supply result order. Component memberships can find rows containing a requested value. Covering regions, space partitions and page-range summaries can exclude groups. The method is useful when the information it retains removes work from the actual question.

Figure 1 What the index keeps
B-treeordered keys → row locators

Find one customer's recent orders, already newest first.

Hashhash codes → row locators

Find rows whose customer ID may equal the supplied ID.

GINcomponent key → row locators

Find arrays containing gift and ceramic.

GiSTcovering summaries → children

Skip branches whose values cannot overlap a query.

SP-GiSTspace partitions → children

Follow the parts of a space the query can reach.

BRINpage-range summary → heap pages

Skip ranges whose timestamps cannot fall on the requested day.

A capability map, not a speed ranking. The class determines the particular keys, summaries, partitions and operators. Several methods can support the same predicate.

The shop wants names beginning with Blue:

SELECT product_id, name FROM products
WHERE name LIKE 'Blue%';

A B-tree can turn a fixed prefix into a narrow search when its comparison puts the relevant strings together. Locale-aware text order can prevent that transformation. In a deterministic non-C collation, text_pattern_ops supplies the character-wise comparison used for the prefix bounds. With the C collation, the default text class already supports this search.

The resulting plan can show special bounds such as name ~>=~ 'Blue' and name ~<~ 'Bluf', followed by a LIKE filter. The bounds locate candidates; the original predicate remains the test. This does not serve LIKE '%mug%', whose unknown beginning supplies no such fixed prefix.

Nor is the pattern class a replacement for every ordinary text comparison. It supports equality, but queries using ordinary <, > or locale-aware ordering need appropriate default-class support. Match the expression, operand types and collation, as well as the column name.

Inspect the definition with pg_get_indexdef. To discover available classes, join pg_opclass to pg_am; opcintype identifies the indexed type. The class belongs to an operator family, which can also contain comparisons between related types. PostgreSQL's psql commands \dAc, \dAf and \dAo list classes, families and operators. An operator's spelling alone does not identify its supported search: array && and range && have different operand types and implementations.

B-tree and hash indexes

The established history request fixes a customer, bounds time, asks for descending time and ID, and stops at ten:

SELECT order_id, placed_at, status FROM orders
WHERE customer_id = 1002
  AND placed_at >= timestamptz '2026-01-01 00:00+00'
ORDER BY placed_at DESC, order_id DESC
LIMIT 10;

CREATE INDEX orders_history ON orders
  (customer_id, placed_at DESC, order_id DESC);

The B-tree's ordered run supports both the time bound and the early stop. A hash index on customer_id can help find that customer's rows, but it supplies no time order. PostgreSQL must test the time condition and sort the eligible results before choosing ten.

A hash index computes a 32-bit hash code and uses it to find a bucket. Each index tuple stores the code and a heap locator, rather than the original customer ID. Different values can have the same code, so a candidate still needs an equality recheck against the heap value. This is a lossy representation: the code has discarded information. The query must not return a different customer merely because their hash codes collide.

Hash supports single-column equality searches. It cannot replace a multicolumn history key, supply range bounds or sorted output, enforce uniqueness, or supply an index-only scan. B-tree supports those capabilities where its class and definition fit the request. Equality alone therefore does not establish that hash is the faster choice. Bucket concentration, overflow pages, key width, caching and the rows fetched all matter.

On the generated shop fixture, compare a common customer's 84,000 orders with customer 1002's 36. A direct bucket lookup does not make 84,000 heap candidates cheap. The native comparison below keeps one secondary index at a time so that the requested order, rather than another index, explains the difference.

GIN indexes and component values

An array's ordinary B-tree order compares whole arrays. It does not place every array containing gift in one run. A Generalized Inverted Index, or GIN, works the other way round: each component key points to the rows containing it.

P7 supplies two keys, gift and ceramic. Each has a posting list of heap locators; a large list can use a posting tree. To find arrays containing both, look up both keys and keep locations present in both lists. Asking for equality instead changes what those same memberships can prove.

Shared keys do not prove array equality
Figure 2. Diagnostic arrays, not additional catalogue products. Exact bitmap, non-null one-dimensional arrays.
Figure as text

Gift and ceramic each lead to all three candidate arrays: original, reversed and extra. Containment accepts all three. Equality rechecks original arrays and accepts only the original order with no extra element.

Containment asks whether each requested element is present. It does not require the array to have exactly those elements or that order. Array equality does. GIN's built-in array_ops supports @>, <@, && and =, but they do not all have the same proof available from component membership.

For this non-null containment example, exact key membership proves the predicate. Equality still needs the original array: the same keys cannot distinguish P7 from the reversed array or the one with an extra element. In the observed native equality plan, all three candidate locations were exact bitmap locations, yet two rows were removed by index recheck. “Exact location” describes where to look, not whether the operator is true.

Bitmap Heap Scan on tag_probe (actual rows=1.00 loops=1)
  Recheck Cond: (tags = '{gift,ceramic}'::text[])
  Rows Removed by Index Recheck: 2
  Heap Blocks: exact=1
  -> Bitmap Index Scan on tag_gin (actual rows=3.00 loops=1)
       Index Cond: (tags = '{gift,ceramic}'::text[])

Selected fields from PostgreSQL 18.6. Sequential scans were discouraged to expose the mechanics on four diagnostic rows; costs, times and other fields are omitted.

GIN does not reconstruct the whole array for an index-only scan, nor does it supply the final product-name or relevance order. A search can identify matching rows and still need heap work and a sort. Keep ORDER BY in the query when the result order matters.

The same inverted structure can index text lexemes or JSONB keys, with different extraction and matching rules. Finding component keys does not itself define stemming, phrases or relevance. Full-text search in PostgreSQL develops that retrieval design. PostgreSQL JSON and structured alternatives chooses JSON operators and classes from the facts being queried.

GiST and SP-GiST indexes

Overlap does not have the same useful ordering as a customer ID. A reservation can begin before another and still overlap it, contain it or end before it. PostgreSQL's built-in range classes support indexed overlap through both GiST and SP-GiST:

CREATE INDEX reservation_during ON reservation_probe
USING gist (during);

SELECT id FROM reservation_probe
WHERE during && tstzrange(
  '2026-11-02 10:30+00', '2026-11-02 11:30+00', '[)');

The stored reservation 7001 is 10:00–11:00 UTC. This search finds it. A search for 11:00–12:00 does not: the existing upper bound is excluded by the half-open [) interval. An index accelerates that operator's meaning; it does not turn adjoining intervals into an overlap.

Generalized Search Tree, or GiST, provides a framework whose internal summaries cover the values below them. A search can reject a child when its summary proves that no value inside can match. Otherwise it follows the child. Different classes define different summaries and tests. A bounding rectangle is a useful geometric example, not the definition of every GiST index.

Space-partitioned GiST, or SP-GiST, instead supports structures which repeatedly divide a search space. Quadtrees, k-d trees and text tries are examples. The partitioning rule determines which children a query can reach. Take two points at (1,1) and (3,3). Add two more at (2,6) and (7,5). Search inside the box from (0,0) to (4,4).

Figure 3 Cover values, or partition their space

Find points inside the box from (0, 0) to (4, 4)

GiST · bounding regions

followskip this region(0, 0)(4, 4)

A child summary covers its values. If its region cannot meet the box, skip the whole child. Bounding regions may overlap.

SP-GiST · space partitions

skipskipskipfollow(0, 0)(4, 4)

A split assigns values to regions of space. Follow the partitions the box can reach, applying the rule again inside each.

Conceptual pruning on points (1,1), (3,3), (2,6) and (7,5). The box returns the first two. Rectangles and split positions are chosen to show the distinction; they are not a dump of PostgreSQL pages. Boundary handling belongs to the class; no point lies on this drawing’s split.

The box contains (1,1) and (3,3). A GiST child whose covering region contains only the two outside points can be excluded as a whole. An SP-GiST split can instead exclude parts of the space the box cannot reach. Different data distributions and query shapes change how much can be pruned. Neither method is one universal spatial index, and neither method name alone tells you whether a leaf match needs rechecking. The selected class determines how much information survives.

The range example uses a built-in type and class. A rule forbidding two reservations for the same room is a separate integrity design: searching for overlap is not by itself a concurrency-safe exclusion rule. Types and extensions in PostgreSQL develops specialised type, operator and extension choices; Constraints and data integrity establishes the rule.

Distance ordering and nearest neighbours

Some GiST and SP-GiST classes also supply a distance-ordering operator. For the native point classes, this lets a search produce the nearest points without sorting every point's distance first:

SELECT id, p <-> point '(0,0)' AS distance
FROM point_probe
ORDER BY p <-> point '(0,0)'
LIMIT 2;

Points (1,1) and (3,3) are also the nearest to (0,0) in that four-point example. An assisted plan shows the distance expression under Order By in its index scan. This order depends on the query point; it is different from a B-tree's fixed value order. Support belongs to the particular class and operand types, so check its documented ordering operators.

This native geometric example does not establish the recall of an approximate embedding index. Vector search in PostgreSQL compares exact and approximate retrieval, filters and recall separately from whether an embedding captures useful meaning.

BRIN indexes and physical correlation

A Block Range Index, or BRIN, can retain much less than one entry per tuple. Its timestamp min/max class records the lowest and highest timestamp in each group of adjacent heap pages. If a requested day cannot lie between them, every page in that range can be skipped.

It cannot identify which tuples match within a surviving range. PostgreSQL collects the pages and tests their tuples. Consider the same timestamps arranged first in increasing order and then mixed across heap pages.

Exclude pages before testing rows
Figure 4. Invented physical layouts. BRIN summaries select ranges; the heap supplies the exact matches.
Figure as text

Day 8 is one of sixteen timestamps on eight pages. In increasing order, two-page ranges select two pages and four tests; one-page ranges select one page and two tests. Mixed order leaves all eight pages and sixteen tests. Every case finds the same match.

Increasing time puts narrow spans in each summary. Mixing distant times across every range broadens the summaries until no range can be excluded. The matching values did not change; the information lost by summarising each physical range did. A timestamp column is therefore not sufficient reason to choose BRIN. Arrival order, backfills and later updates determine whether its values remain usefully correlated with physical placement.

CREATE INDEX orders_time_brin ON orders USING brin (placed_at)
WITH (pages_per_range = 32);

pages_per_range trades summary count for precision. Smaller ranges give more summaries and can exclude more heap pages, while making the index larger. They cannot recover useful separation when even individual pages mix widely separated timestamps. Other BRIN classes retain different summaries, including multiple min/max intervals or Bloom filters; the examples here use ordinary timestamp min/max.

Building BRIN summarises existing ranges. Inserts into summarised ranges update their summaries as needed. Newly extended ranges can remain unsummarised until vacuum or explicit summarisation processes them; autosummarize is off by default. An unsummarised range must remain a candidate, preserving correct results at the cost of extra scanning. An old summary that is too broad can also keep unnecessary pages. The upkeep procedure belongs with PostgreSQL schema changes under load.

Candidates, rechecks and visible rows

A heap visit can answer three different questions. First, does this candidate actually satisfy the indexed operator? Hash collisions, GIN array equality and BRIN summaries can require that index recheck. Second, does another SQL condition pass? A condition on an unindexed stock column is a filter. Third, is this tuple visible to the reader's snapshot? That is the visibility check already developed in Inside PostgreSQL.

There is another way to lose precision: the bitmap itself. A bitmap heap scan collects locations before reading heap pages. With enough memory, it can retain exact tuple positions on a page. Under memory pressure it can keep just the page, requiring the executor to retest tuples there. This can happen even when the original index predicate was exact.

Keep those two losses separate. A GIN equality candidate can have an exact tuple location but an unproved predicate. A B-tree comparison can have a proved predicate but lose its exact tuple location in a page-level bitmap. BRIN already supplies page ranges, so tuple tests are intrinsic to that route.

A focused native check made the second loss visible. A diagnostic copy of the same 120,003 order IDs and timestamps added a constant 512-byte padding column to spread tuples over more pages. With a B-tree timestamp predicate, a forced bitmap route and work_mem=64kB, it reported 811 exact and 7,761 lossy heap blocks, rejecting 44,279 tuples by recheck.

At 4 MiB, it reported 8,572 exact blocks and no recheck rejects. Both returned the same 70,360 order IDs. The padding is an experimental physical width, not another shop fact or an instruction to increase memory globally.

Read the plan as work, rather than a method badge
EvidenceWhat to establish
Index CondThe predicate passed to the index. It can define bounds or test candidates; it does not count every entry examined.
Recheck CondThe predicate available for heap rechecks. Its presence alone does not say how many checks ran or failed.
Rows Removed by Index RecheckCandidates discarded by the indexed predicate, rather than by a separate filter.
Filter and Rows Removed by FilterA separate condition tested at that node, and rows it rejected.
Heap Blocks: exact / lossyBitmap location precision. Exact locations can still carry an operator recheck.
Buffers, actual rows and loopsAccess work and output volume. Buffer accesses can revisit pages; node row counts are per-loop averages when loops exceed one.

Compare returned results before interpreting a faster plan. Then ask how many candidates reached the heap, which tests removed them and which pages were touched. Zero rejected candidates does not prove that no rechecks ran. Conversely, a Recheck Cond line does not establish that any candidate was rejected. Reading and repairing PostgreSQL plans develops the wider diagnosis.

What each method adds to writes

The read saving comes from information maintained during writes. A B-tree maintains ordered entries and may split pages. Hash adds codes to buckets; concentrated values can build overflow chains, and growth can split buckets. GiST maintains covering summaries, while SP-GiST maintains the chosen partitions. The shape and number of affected entries depend on the data and class.

GIN can extract many keys from one row. One new document can therefore add many posting-list memberships. With fastupdate enabled, new entries can first accumulate in a pending list and be merged into the main structure later. Searches must include that list, and an insert that crosses its cleanup threshold can inherit a large cleanup. Deferring work changes when it is paid.

A small native insert comparison made that distinction measurable. Each of 1,000 rows contained the same twenty distinct tag keys. The insert generated 331,241 WAL bytes without an index, 795,933 with default GIN pending entries, and 12,295,046 with fastupdate=off. The pending index then occupied 425,984 bytes, versus 49,152 for the direct-update index.

Those are initial insert observations on separately created empty tables: the pending list had not yet been cleaned. They show why a quick insert and a compact settled index are different measurements; they do not rank lifetime cost or production throughput.

BRIN usually has far fewer summary entries, but an inserted outlier can widen a summary and reduce future pruning. New ranges need summarising. A small index still has a maintenance contract.

An update must also account for PostgreSQL's row versions. Changing a column used by an ordinary index can prevent a HOT update, including expression inputs, included columns and partial-index predicates. Without HOT, unchanged ordinary indexes can also receive entries for the new tuple. BRIN is the summarising exception: a HOT update can still require summary maintenance. Same-page space remains another HOT condition.

Measure a candidate's size, write log and buffer work, plus any deferred cleanup, under the relevant mix of inserts and updates. Do not infer write cost from one definition's column count. Concurrent builds, failed builds and operational cleanup need the procedures in PostgreSQL schema changes under load.

Choosing and checking an access method

Start with the operator and its meaning. Check supported classes for the stored type, expression and collation. Then predict the information that will remove work: an ordered run, component memberships, a region to prune, or a block-range summary. Include the requested order and limit in that prediction.

The native checks use the exact 120,003-order shop fixture already used by the index introduction. Sorted and mixed BRIN copies contain the same rows. Small diagnostic tables isolate array matching, point searches, half-open intervals and prefix comparison. Mechanical demonstrations discourage sequential scans where necessary so that the index route is visible; those demonstrations are not claims that the planner would choose that route on a tiny table.

Observed PostgreSQL 18.6 access work · one execution per listed case
Request and candidateWork observedWhat it establishes
Customer 1002 history · B-tree10 rows from an ordered index scan; 13 shared-buffer accessesThe ten-row limit stopped the ordered scan without a sort.
Same history · hash36 heap rows, then sort; 38 shared-buffer accessesCustomer equality alone did not supply history order.
1 October · BRIN, time-sorted heap32 lossy heap blocks; 4,695 rejected tuples; 329 returnedOne physical range survived the timestamp summaries.
Same day · BRIN, mixed heap768 lossy heap blocks; 119,674 rejected tuples; 329 returnedMixed timestamps prevented useful range exclusion.

The two BRIN queries returned identical sets of order IDs. Both used pages_per_range=32; the sorted heap occupied 6 MiB and its index 24 KiB. Their routes were exposed with sequential scans discouraged. The history queries used normal scan settings, one secondary index at a time. Buffer accesses count hits plus reads, including repeat accesses, rather than distinct pages or drive operations.

In the deterministic ICU prefix test, the default text index left the query as a sequential scan. Adding text_pattern_ops produced the Blue–Bluf bitmap search and retained the original LIKE filter. GiST and SP-GiST point queries both returned points 1 and 2 and showed index-assisted distance ordering. These checks establish supported searches; they do not establish a performance winner between the frameworks.

The recorded plans and results retain the complete counters. The method verifier and focused bitmap verifier include their generated fixture, settings and exact safety guards. They require the specifically named disposable database, user and cluster and roll their changes back. They record these observations rather than supplying commands for an application database.

For an application choice, restore the normal planner settings and test representative values and layouts. Compare common and rare customers, narrow and broad bounds, stable and recently changed pages. Check the complete ordered result, then the actual plan and buffers. Finally test the write workload and cleanup over time. Keep an index only when the useful work it removes earns its ongoing cost.

Sources and further reading

Checked against PostgreSQL 18 documentation. Drawings are conceptual models. SQL semantics were also checked in PGlite 0.5.8, PostgreSQL 18.3 compiled to WebAssembly; the server plans use native PostgreSQL 18.6. Neither runtime establishes production latency.