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.
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 sizeFROM pg_classWHERE 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)::intFROM generate_series(1, 300000) g;VACUUM ANALYZE page_views;ALTER DATABASE riverside SET max_parallel_workers_per_gather = 0;
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.