Sub topic 3
BRIN: tiny indexes for large, naturally ordered tables
This chapter assumes you can write SQL SELECT and WHERE clauses, create tables in PostgreSQL, and read a basic EXPLAIN plan.
A BRIN (Block Range INdex) stores one summary per group of table pages, usually the minimum and maximum value in that group. A B-tree stores an entry for every row, so a BRIN index is often hundreds of times smaller. It works only when the column's values follow the physical order of the rows, such as a timestamp on append-only log data. If the values are scattered, each block range has a wide min/max span, and the index skips almost nothing.
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);
EXPLAIN (ANALYZE, BUFFERS)
SELECT avg(value)
FROM measurements
WHERE recorded_at >= now() - interval '1 day';Look for Bitmap Index Scan on measurements_recorded_brin_idx in the plan. The pages_per_range setting controls how many table pages share one summary. Smaller values give a more precise index and a larger index size.
Write cost, size, and maintenance
Every index adds work to inserts, updates, and deletes. Build an index on a busy table with CREATE INDEX CONCURRENTLY, which avoids blocking writes:
CREATE INDEX CONCURRENTLY orders_status_idx ON orders (status);
SELECT indexrelname, idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE relname = 'orders'
ORDER BY idx_scan;> Note: CREATE INDEX CONCURRENTLY cannot run inside a transaction block. If the build fails, it can leave an invalid index behind, so drop it and retry.
An index with a low idx_scan count over a long period costs space and write time for little benefit.
Choosing an index type for your workload
| Index type | Best for | Main limitation |
|---|---|---|
| B-tree | Equality, ranges, ORDER BY | Large on very big tables |
| Hash | Equality only | No ranges or ordering |
| GIN | jsonb, arrays, full-text search | Slower writes |
| GiST | Geometry, ranges, nearest neighbor | Larger and slower than B-tree for plain values |
| BRIN | Huge tables with ordered values | Needs physical row order |
Exercise
A table of 500 million log rows is appended in time order, and queries filter on the last few hours. Which index type should you use, and why?
Show answer
BRIN on the timestamp column. Appended rows keep the timestamps in physical order, so the small block-range summaries skip most of the table while the index stays tiny.