Sub topic 9
BRIN: Tiny Indexes for Large, Naturally Ordered Tables
Prerequisites and the core idea
Assume you know basic SELECT, WHERE, and CREATE INDEX statements, and that you have used PostgreSQL's EXPLAIN command.
A BRIN index, or Block Range INdex, summarizes groups of table pages instead of storing one entry for every row. A table page is a fixed-size storage block, usually 8 KB. A BRIN index records summary values for a range of nearby pages.
For a timestamp column, the summary usually contains the minimum and maximum timestamp in each page range. PostgreSQL can skip a range when its summary proves that the range cannot contain a requested value.
BRIN works when column values are correlated with physical row order. For example, a measurement table that receives new rows in increasing timestamp order has strong correlation between recorded_at and the location of each row on disk.
Creating and using a BRIN index
The following table stores sensor measurements in roughly recording-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 controls how many table pages share one summary. A smaller value creates more summaries. This can improve filtering precision, but it makes the BRIN index larger. A larger value makes the index smaller, but each summary covers more rows and may be less selective.
BRIN does not return the final rows directly. It identifies page ranges that might match. PostgreSQL then reads those pages and rechecks the actual rows. This is called a lossy index scan. Lossy means that the summary may include extra pages, but it must not exclude a page that contains a valid match.
Reading the query plan
Use EXPLAIN (ANALYZE, BUFFERS) to check whether PostgreSQL uses the BRIN index and how many rows it rechecks:
EXPLAIN (ANALYZE, BUFFERS)
SELECT avg(value)
FROM measurements
WHERE recorded_at >= now() - interval '1 day';A useful plan may contain Bitmap Index Scan on the BRIN index followed by Bitmap Heap Scan. In the heap scan, look for information such as Rows Removed by Index Recheck. Some removed rows are expected because BRIN summaries describe page ranges rather than individual rows.
Compare the number of table blocks read with the table's total size. A BRIN index can be useful even when it examines some extra rows, because the query may avoid reading most of a very large table.
The planner may choose a sequential scan when the condition matches a large part of the table, when the table is small, or when statistics show that the index will not save enough I/O. Index existence does not guarantee index usage.
When BRIN is a good fit
BRIN is especially useful for append-only or mostly append-only tables:
- Event logs ordered by event time.
- Time-series measurements ordered by recording time.
- Audit tables where rows are inserted in increasing identifier order.
- Very large tables where a B-tree would consume substantial storage.
BRIN is usually a poor fit when values are randomly distributed across the table. For example, if rows are constantly updated and moved conceptually across many unrelated values, each page range may have a very wide minimum-to-maximum span. Such summaries cannot eliminate many ranges.
BRIN can index more than timestamps. PostgreSQL provides operator classes for suitable data types, including numeric, date, timestamp, and some network and geometric types. The operator class determines which comparisons the summary can support.
Summarization and maintenance
PostgreSQL creates summaries as it builds a BRIN index. New table pages may not be summarized immediately. PostgreSQL can summarize them during later maintenance, or you can request summarization explicitly:
VACUUM (ANALYZE) measurements;
SELECT brin_summarize_new_values('measurements_recorded_brin_idx');The function returns the number of newly summarized page ranges. Check the function and index name against your PostgreSQL version before using it in automation.
Updates can weaken physical correlation. If the table is frequently updated, periodically inspect query plans and consider whether a B-tree performs better. A BRIN index has low storage and update cost compared with a B-tree, but its usefulness depends on the data's physical layout.
Choosing `pages_per_range`
Start with the default or a moderate value, then measure. Reduce pages_per_range when queries read too many false-positive pages and the extra index size is acceptable. Increase it when the index is larger than needed and the summaries remain selective.
Do not choose the value from the column type alone. Test with representative data, realistic predicates, and EXPLAIN (ANALYZE, BUFFERS).
Exercise
A 2-terabyte log table stores rows in increasing created_at order. Queries usually filter on recent time ranges. Which index type is a strong first candidate, and what property makes it suitable?
Show answer
A BRIN index is a strong first candidate because nearby table pages contain nearby created_at values. Its min/max summaries can skip old page ranges while keeping the index very small.