AI Hints
Home›PostgreSQL Tutorial›GIN, BRIN and Index Mistakes
PostgreSQL · Lesson 56 of 120

BRIN Indexes

Tiny indexes for huge tables.

⏱ 2 min read▶ Video at 49:33🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Page views arrive in time order, so rows near each other on disk have similar times. A BRIN index just stores the minimum and maximum for each block of rows. It's tiny, but very effective for this kind of data.

  • Rows in time order
  • Min and max per block
  • Tiny

BRIN vs B-tree size

We build a B tree and a BRIN index on viewed at, and compare their sizes. Run it. The BRIN index is a tiny fraction of the B tree's size.

query.sqlsql
CREATE INDEX views_time_btree ON page_views (viewed_at);
CREATE INDEX views_time_brin  ON page_views USING brin (viewed_at);

SELECT relname AS index, pg_size_pretty(pg_relation_size(oid)) AS size
FROM pg_class
WHERE relname IN ('views_time_btree', 'views_time_brin');
Output
CREATE INDEX
CREATE INDEX
      index       |  size
------------------+---------
 views_time_btree | 6600 kB
 views_time_brin  | 24 kB
(2 rows)
Also uses _setup.sql
SELECT setseed(0.42);
CREATE TABLE page_views (
  view_id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id integer NOT NULL,
  book_id     integer NOT NULL,
  device      text NOT NULL,
  viewed_at   timestamptz NOT NULL,
  ms          integer NOT NULL);
INSERT INTO page_views (customer_id, book_id, device, viewed_at, ms)
SELECT 1 + (random() * 499)::int, 1 + (random() * 29)::int,
       (ARRAY['web','web','web','app','app'])[1 + (random() * 4)::int],
       timestamptz '2025-01-01' + (g * interval '100 seconds'),
       50 + (random() * 900)::int
FROM generate_series(1, 300000) g;
VACUUM ANALYZE page_views;
ALTER DATABASE riverside SET max_parallel_workers_per_gather = 0;

When BRIN fits

BRIN works when values follow the physical order, like timestamps in an append only log. It's great for huge tables, like logs, events and sensor data. If rows are shuffled, BRIN can't skip much.

keyvalue
Best fortime-ordered data
Sizekilobytes
Tableshuge logs, events
Shuffled datanot useful

Summary

BRIN indexes store ranges per block, tiny and great for time ordered data. Next, common index mistakes.

Key takeaways
  • BRIN
  • Min/max
  • Tiny
Next up: Index Mistakes — why it is not used