← Back to SQL, page 20

sql-0386 · Hard senior

What is a BRIN index in PostgreSQL, and when does it beat a B-tree?

A BRIN (block range) index stores only the minimum and maximum value for each range of table pages. It is tiny and cheap to maintain, and it works well when the column's values correlate with physical order, such as an append-only timestamp. For random data it is nearly useless, because every range overlaps the search.

Full answer

How it works: for each block range (128 pages by default), BRIN records the min and max of the column. A query for ts >= '2026-03-01' skips ranges whose max is earlier and reads the rest.

Where it shines:

  • Append-only logs and sensor data where rows arrive in time order.
  • Very large tables where a B-tree would be gigabytes; a BRIN index may be a few hundred kilobytes.
  • Insert-heavy workloads, since maintenance is minimal.

Limitations:

  • Results are lossy: matching ranges are scanned and rows rechecked, so point lookups are slower than with a B-tree.
  • Updates or out-of-order inserts break the correlation and widen ranges.
  • No uniqueness, no index-only scans.

Check pg_stats.correlation for the column; values near 1 or -1 suggest BRIN will help. This is described from PostgreSQL documentation and was not run here.

Key points

  • BRIN stores min and max per block range
  • Tiny and cheap to maintain
  • Needs correlation with physical order
  • Lossy, so rows are rechecked
  • Check pg_stats.correlation

Common mistakes

  • Using BRIN on randomly ordered columns
  • Expecting fast point lookups from BRIN

Follow-ups

  • How does pages_per_range affect BRIN?
  • Could partitioning replace a BRIN index?

Tips

  • Tie BRIN to physical order