pgstattuple Measures Dead And Free Space

Inspect dead tuples and reusable free space with pgstattuple before and after VACUUM: deletes raise dead_tuple_percent, VACUUM converts them into free_percent.

SqlResilience

Code

snippet
CREATE EXTENSION IF NOT EXISTS pgstattuple;

CREATE TABLE page_probe (id int PRIMARY KEY, payload text NOT NULL);

INSERT INTO page_probe
SELECT g, repeat('x', 200) FROM generate_series(1, 20000) g;

-- 半数行被删除:空间先挂在 dead_tuple_percent 上,free_percent 还没涨
DELETE FROM page_probe WHERE id % 2 = 0;

SELECT table_len, tuple_count, tuple_percent, dead_tuple_percent, free_percent
FROM pgstattuple('page_probe');

-- VACUUM 把死元组腾成可复用空间:dead 归零、free_percent 上升,表长不变
VACUUM page_probe;

SELECT table_len, tuple_count, tuple_percent, dead_tuple_percent, free_percent
FROM pgstattuple('page_probe');

Inside the snippet

The file runs SELECT / INSERT / DELETE / CREATE statements, touching page_probe, generate_series and pgstattuple.

Breaking the statements into their working parts: a WHERE clause that keeps only the rows a statement is meant to touch; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Putting it to use

Run the statement against the page_probe table.

Core lines

INSERT INTO page_probe
SELECT g, repeat('x', 200) FROM generate_series(1, 20000) g;
SELECT table_len, tuple_count, tuple_percent, dead_tuple_percent, free_percent
FROM pgstattuple('page_probe');
CREATE TABLE page_probe (id int PRIMARY KEY, payload text NOT NULL);

Interactive Tools for This Topic

FAQ

Which relations are involved here?
The references are `page_probe`, `generate_series`, `pgstattuple`.