PostgreSQL BRIN Index Time Series
Index append-only time series with tiny BRIN blocks, comparing size against B-tree for range scans over billions of rows.
Code
-- PostgreSQL 时序表按写入时间自然有序(append-only)
CREATE TABLE metrics (
observed_at timestamptz NOT NULL,
sensor_id int NOT NULL,
value double precision NOT NULL
) WITH (fillfactor = 100);
-- BRIN 索引:按块范围记录最小最大值
CREATE INDEX idx_metrics_observed_brin
ON metrics USING brin (observed_at)
WITH (pages_per_range = 32);
-- 范围扫描:块范围过滤掉绝大多数数据块
SELECT sensor_id, avg(value)
FROM metrics
WHERE observed_at >= '2026-10-21 00:00'
AND observed_at < '2026-10-22 00:00'
GROUP BY sensor_id;
-- 尺寸对照:B 树版本用于体积感知
CREATE INDEX idx_metrics_observed_btree
ON metrics (observed_at);
-- 验证计划选择
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*)
FROM metrics
WHERE observed_at >= '2026-10-21'
AND observed_at < '2026-10-22';
-- 老数据分区后 BRIN 更精准:每分区独立建
CREATE TABLE metrics_old PARTITION OF metrics
FOR VALUES FROM ('2026-01-01') TO ('2026-10-01');How the snippet works
Several statements share this file — SELECT / CREATE / EXPLAIN, with metrics among the objects involved.
The SQL constructs in play: a WHERE clause narrowing which rows one statement affects; COUNT, AVG aggregation; a GROUP BY that collapses matching rows into one output row per group; NOT NULL qualifiers on the required columns.
Applying it
Point it at the metrics table.
Statements that matter
SELECT sensor_id, avg(value)
FROM metrics
WHERE observed_at >= '2026-10-21 00:00'
AND observed_at < '2026-10-22 00:00'
GROUP BY sensor_id;
CREATE TABLE metrics (
observed_at timestamptz NOT NULL,
sensor_id int NOT NULL,
value double precision NOT NULL
) WITH (fillfactor = 100);
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*)
FROM metrics
WHERE observed_at >= '2026-10-21'
AND observed_at < '2026-10-22';
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.
FAQ
- What are the relations in play here?
- `metrics` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.