pgstatindex Reports Btree Leaf Density
Read leaf density and fragmentation from pgstatindex: freshly built btrees sit near the 90 fillfactor and decay upward in deleted pages as rows churn.
Code
CREATE EXTENSION IF NOT EXISTS pgstattuple;
CREATE TABLE tag_index_demo (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tag text NOT NULL
);
CREATE INDEX idx_tag_index_demo_tag ON tag_index_demo (tag);
INSERT INTO tag_index_demo (tag)
SELECT 'tag-' || g FROM generate_series(1, 20000) AS g;
-- 刚构建的 btree:叶子页密度贴近 fillfactor 默认值 90,碎片接近 0
-- 默认只有 pg_stat_scan_tables 角色有 EXECUTE 权限
SELECT version, tree_level, index_size, root_block_no,
internal_pages, leaf_pages, empty_pages, deleted_pages,
avg_leaf_density, leaf_fragmentation
FROM pgstatindex('idx_tag_index_demo_tag');
-- index_size 通常比各页计数之和多一页:那是索引的元页(metapage)
-- 大量删除/更新后 deleted_pages 与 leaf_fragmentation 上升、
-- avg_leaf_density 跌离 90,就是 REINDEX 的信号
SELECT relname, n_dead_tup, last_vacuum, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'tag_index_demo';How it works
What runs here is SELECT / INSERT / CREATE — tag_index_demo, generate_series, pgstatindex and pg_stat_user_tables are the objects involved.
Breaking the statements into their working parts: a WHERE clause limiting a statement to the rows that qualify; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Putting it to use
The tag_index_demo table is the working surface here.
Core lines
SELECT relname, n_dead_tup, last_vacuum, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'tag_index_demo';
INSERT INTO tag_index_demo (tag)
SELECT 'tag-' || g FROM generate_series(1, 20000) AS g;
SELECT version, tree_level, index_size, root_block_no,
internal_pages, leaf_pages, empty_pages, deleted_pages,
avg_leaf_density, leaf_fragmentation
FROM pgstatindex('idx_tag_index_demo_tag');
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.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Which tables does the SQL touch?
- `tag_index_demo`, `generate_series`, `pgstatindex`, `pg_stat_user_tables` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.