Pg Prewarm Loads Relation Cache

Load a table or index into shared_buffers with pg_prewarm before benchmarking, so the first measured run does not pay the cold-cache disk read cost.

SqlResilience

Code

snippet
-- pg_prewarm 在扩展里,先启用(contrib 模块自带)
CREATE EXTENSION IF NOT EXISTS pg_prewarm;

-- 把整张表读进 shared_buffers:返回值是实际预热的块数
SELECT pg_prewarm('orders');
--  pg_prewarm
-- ----------
--        728

-- 预热前先看表占多大:pg_relation_size 按字节返回主堆大小,
-- 换算成 shared_buffers 的块数(默认每块 8KB)就能预估预热成本
SELECT pg_size_pretty(pg_relation_size('orders')) AS heap_bytes,
       pg_relation_size('orders') / 8192          AS heap_blocks;

-- 只热表的一部分:first_block / last_block 按块号圈范围,
-- 大表预热首段即可让最热的最近数据常驻缓存
SELECT pg_prewarm('orders', 'buffer', 'main', 0, 99);

-- 预热索引同样有效:只热查询真正用的那棵树
SELECT pg_prewarm('idx_orders_created_at');

-- 对比验证:预热后跑目标查询,BUFFERS 里 shared read 应降为 0
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*)
FROM orders
WHERE created_at >= '2026-01-01';

How it works

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

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; COUNT aggregation.

Using it

The orders table is the working surface here.

Key statements

EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*)
FROM orders
WHERE created_at >= '2026-01-01';
SELECT pg_size_pretty(pg_relation_size('orders')) AS heap_bytes,
       pg_relation_size('orders') / 8192          AS heap_blocks;
SELECT pg_prewarm('orders', 'buffer', 'main', 0, 99);

Interactive Tools for This Topic

FAQ

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