Video in progress

What does the `CLUSTER` command do, and how does the table's physical order (correlation) affect query speed?

CLUSTER physically rewrites the table in the order of a chosen index. Then range queries read the needed rows from fewer pages. But the order isn't maintained by later writes, and the command blocks the table completely for its whole run.

📖 Answer

The planner looks at pg_stats.correlation: how well the order of a column's values matches the on-disk order of the rows. If it's close to 1, an index scan for WHERE created_at BETWEEN ... reads consecutive pages. If it's close to 0, every row is on a different page, so 10,000 rows means 10,000 random page reads.

SELECT attname, correlation
FROM pg_stats
WHERE tablename = 'orders' AND attname IN ('created_at', 'customer_id');

created_at is usually naturally ordered (rows are added in time order). customer_id isn't: one customer's orders are scattered across the table.

If the main query is "all of a customer's orders":

CLUSTER orders USING orders_customer_id_idx;
ANALYZE orders;

But:

  • CLUSTER takes an ACCESS EXCLUSIVE lock and rewrites the whole table, so on a big table in prod it's nearly unusable. pg_repack --order-by does something close to it without locking.
  • New rows don't keep the order, so over time the correlation drops again.

Often other ways are better: an index-only scan with a covering index, or partitioning the data by customer. A BRIN index, on the other hand, is effective precisely on columns with high correlation.