CLUSTER Table Rows By Index Order

Physically reorder a table with CLUSTER and watch pg_stats.correlation move toward 1, which makes range scans cheaper for the planner to choose.

SqlData Fetching

Code

snippet
CREATE INDEX users_created_at_idx ON users (created_at);

-- 排簇前:correlation 反映 created_at 逻辑顺序与物理行序的接近程度,
-- 接近 0 说明行在堆里近乎随机分布,范围扫描要跳着读页
SELECT attname, correlation
FROM pg_stats
WHERE tablename = 'users' AND attname = 'created_at';

-- CLUSTER 按索引顺序物理重写整表;执行期间持有 ACCESS EXCLUSIVE 锁
CLUSTER users USING users_created_at_idx;

-- CLUSTER 不刷新统计:ANALYZE 之后 pg_stats 才反映新的物理顺序
ANALYZE users;
SELECT attname, correlation
FROM pg_stats
WHERE tablename = 'users' AND attname = 'created_at';

-- 注意:CLUSTER 是一次性操作,之后的写入不再保持物理顺序;
-- 不带 USING 的 CLUSTER 会沿用上次使用的索引

How it works

Several statements share this file — SELECT / CREATE, with pg_stats among the objects involved.

In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects.

Putting it to use

Run it in the pg_stats database context.

Core lines

SELECT attname, correlation
FROM pg_stats
WHERE tablename = 'users' AND attname = 'created_at';
CREATE INDEX users_created_at_idx ON users (created_at);
CLUSTER users USING users_created_at_idx;

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`pg_stats`.