实现说明
一个文件里不止一条语句:SELECT / INSERT / UPDATE / DELETE / CREATE / ALTER,metrics、generate_series、pg_stat_user_tables 都在涉及之列。
metrics 是文件自己造的会话级临时表——库里不会有残留,会话终结即被清理。
语句实际拼装出的结构:WHERE 决定这条语句会作用到哪些行;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。
常见问题
说出这个文件涉及的表。
metrics、generate_series、pg_stat_user_tables——以名字直接引用,不经过连接环节。
核心语句
SELECT n_live_tup, n_dead_tup, last_vacuum, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'metrics';
INSERT INTO metrics SELECT g, g * 1.5 FROM generate_series(1, 1000) g;
UPDATE metrics SET value = value * 2 WHERE id % 10 = 0;
代码示例
-- UPDATE/DELETE only mark old tuples dead: the space waits for VACUUM to reclaim it
CREATE TEMP TABLE metrics (
id integer PRIMARY KEY,
value numeric NOT NULL
);
INSERT INTO metrics SELECT g, g * 1.5 FROM generate_series(1, 1000) g;
-- a wide update and delete produce dead tuples
UPDATE metrics SET value = value * 2 WHERE id % 10 = 0;
DELETE FROM metrics WHERE id % 50 = 0;
-- observe the dead tuple count and the last cleanup time (stats views lag slightly; not exact)
SELECT n_live_tup, n_dead_tup, last_vacuum, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'metrics';
-- manual reclaim: space is marked reusable, reads and writes stay unlocked, the table does not shrink
VACUUM metrics;
-- autovacuum trigger threshold = autovacuum_vacuum_threshold (default 50)
-- + autovacuum_vacuum_scale_factor (default 0.2) × estimated row count
-- the scale factor is the backstop for big tables: a 100k-row table waits for ~20k dead tuples; tighten per table for hot ones
ALTER TABLE metrics SET (autovacuum_vacuum_scale_factor = 0.02);