Sub topic 9
BRIN: Tiny Indexes for Large, Naturally Ordered Tables
This chapter assumes you can read a basic EXPLAIN (ANALYZE, BUFFERS) plan and know how a B-tree index serves range predicates. It also assumes you know that PostgreSQL stores table rows (the heap) in 8 kB pages. Earlier chapters covered both.
A BRIN index (Block Range INdex) takes the opposite approach from a B-tree. A B-tree stores one entry per row. A BRIN index stores one small summary per group of adjacent heap pages. The index stays tiny, but it only works when the physical order of rows matches the order of the indexed values.
What a BRIN index stores
A BRIN index divides the table into block ranges, which are runs of consecutive heap pages. The default is 128 pages, or 1 MB. For each range it stores a summary of the indexed column's values in those pages. With the default minmax operator class, the summary is the smallest and largest value in the range.
A BRIN index can't point to individual rows. When you run a query, PostgreSQL does the following:
- It compares the query condition with each range summary.
- It skips every range whose min/max interval cannot contain a match.
- It reads all the pages of the remaining ranges and re-checks the condition on each row.
Because the index gives page ranges and not row locations, BRIN scans are always lossy. They appear in plans as a Bitmap Index Scan feeding a Bitmap Heap Scan. The index narrows the search to some ranges, and the heap scan filters the rows.
Creating a BRIN index
The example below uses the measurements table, which receives readings in time order:
CREATE TABLE measurements (
recorded_at timestamptz NOT NULL,
sensor_id integer NOT NULL,
value double precision
);
CREATE INDEX measurements_recorded_brin_idx
ON measurements USING brin (recorded_at)
WITH (pages_per_range = 64);
SELECT avg(value)
FROM measurements
WHERE recorded_at >= now() - interval '1 day';pages_per_range sets how many heap pages each summary covers. Here each summary covers 64 pages, or 512 kB. The query asks for the last day of data. In an append-only table those rows sit in the last few block ranges, so PostgreSQL can skip the rest.
Compare size against a B-tree
To see the size difference, load some synthetic data that arrives in time order and build both index types:
INSERT INTO measurements (recorded_at, sensor_id, value)
SELECT timestamptz '2026-01-01 00:00:00+00' + g * interval '1 second',
g % 100,
random()
FROM generate_series(1, 5000000) AS g;
CREATE INDEX measurements_recorded_btree_idx
ON measurements (recorded_at);
ANALYZE measurements;
SELECT relname,
pg_size_pretty(pg_relation_size(oid)) AS size
FROM pg_class
WHERE relname IN ('measurements',
'measurements_recorded_brin_idx',
'measurements_recorded_btree_idx')
ORDER BY pg_relation_size(oid);On a typical installation the BRIN index takes tens of kilobytes. The B-tree takes on the order of 100 MB, and the table itself is a few hundred megabytes. The BRIN size depends on the number of block ranges, not the number of rows. For a table of any size, doubling pages_per_range roughly halves the index.
To compare the plans, drop the B-tree index and look at a one-day slice:
DROP INDEX measurements_recorded_btree_idx;
EXPLAIN (ANALYZE, BUFFERS)
SELECT avg(value)
FROM measurements
WHERE recorded_at >= timestamptz '2026-01-10 00:00:00+00'
AND recorded_at < timestamptz '2026-01-11 00:00:00+00';The plan should contain nodes shaped like this (your numbers will differ):
Bitmap Heap Scan on measurements
Recheck Cond: ((recorded_at >= ...) AND (recorded_at < ...))
Rows Removed by Index Recheck: ...
Heap Blocks: lossy=...
-> Bitmap Index Scan on measurements_recorded_brin_idxHeap Blocks: lossy=N shows that the bitmap tracks whole pages, not individual rows. Rows Removed by Index Recheck counts rows PostgreSQL read from the selected ranges that didn't match. A large value means the ranges are too coarse or the data is not well ordered.
Correlation: the condition that makes BRIN work
BRIN helps only when values in nearby pages are close together in value. Statistics collected by ANALYZE measure this as correlation, a number from -1 to 1. It compares the physical row order with the sorted order of the column.
SELECT attname, correlation
FROM pg_stats
WHERE schemaname = 'public'
AND tablename = 'measurements';A value near 1 (ascending) or -1 (descending) means rows are stored almost in sorted order, and BRIN works well. A value near 0 means values are scattered. In that case every block range's min/max interval spans nearly the whole value domain, so no range can be skipped.
The planner uses the correlation statistic when it estimates the cost of a BRIN scan. If correlation is low, it will prefer a sequential scan, and rightly so.
Physical order degrades over time
The index does not keep the table ordered. It only describes the order the heap already has. These events change that order:
- Appends in time order keep the order intact. This is the ideal workload.
- Updates write a new row version, possibly in a different page, often one with free space. A recent timestamp can end up inside an old block range. That range's max grows, and its interval now overlaps many queries.
- Deletes followed by inserts let new rows fill freed space in old pages. This has the same effect as updates.
- Backfills of old data into the end of the table put out-of-order values in recent ranges.
A summary only widens; it never narrows. Even if the outlier row is later deleted, the range keeps its wide interval until it is re-summarized or the index is rebuilt. If a table has drifted, CLUSTER rewrites it in the order of a B-tree index. It takes an ACCESS EXCLUSIVE lock and doesn't maintain the order afterward. REINDEX rebuilds a BRIN index so its summaries match the current data.
Summarization of new ranges
When you create the index, every existing range is summarized. After that, inserts that land in an already summarized range update its summary immediately. New pages added past the end of the table start a new range with no summary. An unsummarized range is always included in scan results, because PostgreSQL can't prove it holds no matches.
A range gets summarized in one of three ways:
VACUUM(including autovacuum) summarizes the ranges that are still unsummarized.- The index storage parameter
autosummarize = onasks autovacuum to summarize a range soon after the range fills up. It is off by default. - You can call
brin_summarize_new_values()yourself.
ALTER INDEX measurements_recorded_brin_idx
SET (autosummarize = on);
SELECT brin_summarize_new_values('measurements_recorded_brin_idx');The function returns how many ranges it summarized. On a busy append-only table the newest range is often unsummarized, which is harmless. At most one range per scan is read unconditionally, and recent data tends to be what queries want anyway.
Choosing `pages_per_range`
pages_per_range trades index size against precision.
| Setting | Index size | Precision | Typical use |
|---|---|---|---|
| Small (8 to 32) | Larger | Reads fewer unneeded pages | Selective queries on well-ordered data |
| Default (128) | Very small | Reasonable | Most append-only tables |
| Large (256 or more) | Smallest | Reads more unneeded pages | Very large tables, wide queries, scans over most of the data |
The right value depends on how many rows a query returns relative to the range size. A query returning 1% of a table gets little benefit from ranges that each cover 5% of it. Test two or three values with EXPLAIN (ANALYZE, BUFFERS) and compare Heap Blocks and Rows Removed by Index Recheck.
Other operator classes
The default minmax class supports <, <=, =, >=, and > on most ordered types. PostgreSQL 14 added more classes that handle weaker ordering:
*_minmax_multi_ops(for exampletimestamptz_minmax_multi_ops) stores several min/max intervals per range. A few outliers then no longer stretch the whole summary.*_bloom_ops(for exampleint4_bloom_ops) stores a Bloom filter per range. It supports only equality, but it can work on a column with no physical ordering, at the price of false positives.*_inclusion_ops(for examplerange_inclusion_opsorbox_inclusion_ops) stores a bounding value, which makes BRIN usable for ranges, network addresses, and geometric types.
CREATE INDEX measurements_recorded_multi_idx
ON measurements USING brin (recorded_at timestamptz_minmax_multi_ops);
CREATE INDEX measurements_sensor_bloom_idx
ON measurements USING brin (sensor_id int4_bloom_ops);A multicolumn BRIN index summarizes each column independently. Unlike a multicolumn B-tree, the column order does not matter.
Limits and decision criteria
BRIN is not a general replacement for B-tree. These are the main differences:
- A BRIN index cannot enforce uniqueness, so it cannot back a primary key or a unique constraint.
- It cannot return rows in sorted order, so it does not help
ORDER BY ... LIMIT. - It does not support index-only scans, because it stores no per-row values.
- It is poor for point lookups returning a handful of rows, since PostgreSQL must read every page of each matching range.
- It is a poor fit for small tables. A sequential scan is already cheap, and B-tree overhead is not a problem there.
BRIN is a good fit when all of the following hold:
- The table is large, often tens of gigabytes or more.
- The indexed column correlates strongly with physical order (a timestamp or a monotonically increasing ID on an append-only table).
- Queries select a range containing a modest slice of the table.
- Index size and write overhead matter, because BRIN adds almost nothing to insert cost.
Summary
BRIN stores one summary per block range, so its size depends on table size in pages and pages_per_range, not row count. It skips ranges whose summary cannot match and reads the remaining ranges in full, then rechecks each row. The result is always lossy. It works when correlation is near 1 or -1, degrades after out-of-order updates, and needs new ranges to be summarized.
Exercise
A table logs(created_at timestamptz, user_id integer, message text) is append-only, and rows are inserted in time order. A colleague proposes CREATE INDEX ON logs USING brin (user_id) to speed up WHERE user_id = 7. Why is this likely to fail, and what do you check or change?
Show answer
Rows are ordered by created_at, not by user_id, so each block range probably contains many different user IDs. Each range's min/max interval for user_id then spans nearly all values, and the index can't skip any range. Check correlation for user_id in pg_stats. A value near 0 confirms the problem. Use a B-tree on user_id for this lookup instead. A int4_bloom_ops BRIN index is another option if you need a small index for equality on an unordered column. A BRIN index on created_at is the one that matches the data's physical order.
Exercise
After a bulk update touched many old rows in a large time-series table, a BRIN query that used to read a few hundred pages now reads most of the table, and Rows Removed by Index Recheck is very high. Why, and how can you fix it?
Show answer
The updates wrote new row versions into pages across the table, including old block ranges. Those ranges' min/max summaries widened to include recent timestamps, and summaries never narrow, so many ranges now overlap the query. To fix it, restore physical order with CLUSTER on a B-tree index of the column (which takes an exclusive lock and rewrites the table) or by reloading the data in order. Then rebuild the BRIN index with REINDEX. A minmax_multi operator class can also reduce the damage when only a few outliers are involved.