← 中文资源

简体中文版本

correlation 统计诊断物理行序

ANALYZE 后读取 pg_stats.correlation:绝对值接近 1 说明物理行序与逻辑序几乎一致、扫描接近顺序读;接近 0 表示每行都要随机 IO。

阅读英文原文

核心语句

INSERT INTO events_seq (occurred_at)
SELECT now() - (n || ' minutes')::interval
FROM generate_series(1, 20000) AS n;
SELECT attname, correlation
FROM pg_stats
WHERE tablename = 'events_seq' AND attname = 'occurred_at';
CREATE TABLE events_seq (
occurred_at timestamptz NOT NULL,
payload text NOT NULL DEFAULT 'event'
);

代码示例

-- pg_stats.correlation compares a column's physical storage order with its
-- logical order (the order ORDER BY on the column would produce).
-- |correlation| near 1: scanning by this column reads the heap almost
-- sequentially. Near 0: rows are scattered and every fetch risks random I/O.
CREATE TABLE events_seq (
    occurred_at timestamptz NOT NULL,
    payload text NOT NULL DEFAULT 'event'
);

-- Rows land in descending time order here, so physical order mirrors the
-- logical order exactly (reversed): the statistic should come out near ±1.
INSERT INTO events_seq (occurred_at)
SELECT now() - (n || ' minutes')::interval
FROM generate_series(1, 20000) AS n;

-- The statistic is produced by ANALYZE: without it pg_stats has no row to show.
ANALYZE events_seq;

SELECT attname, correlation
FROM pg_stats
WHERE tablename = 'events_seq' AND attname = 'occurred_at';

-- Read the value as a storage-layout diagnostic: near ±1 the column is stored
-- contiguously in logical order, so ordered range scans stay sequential; near
-- 0 the same scans degrade into random I/O, and rebuilding the table with rows
-- in key order (CLUSTER on a matching index) restores the sequential layout.