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.
Code
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
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.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.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Name the tables involved in this file.
- `pg_stats`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.