brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: pgstattuple_approx estimates PostgreSQL table bloat without reading the whole table

Postgresql
~/tips/tip-postgresql-pgstattuple-approx

CREATE EXTENSION pgstattuple;

Reports dead tuples and free space of a table, skipping pages that the visibility map marks clean.

Autovacuum numbers tell you what PostgreSQL thinks about a table. If you want to see how much of the file is dead rows or empty space, a contrib extension counts it for you.

CREATE EXTENSION pgstattuple;
SELECT dead_tuple_percent, free_percent
FROM pgstattuple_approx('my_table');

Plain pgstattuple('my_table') reads the whole table and gives exact figures: live and dead tuples, and free space, in bytes and as percentages. That is expensive on a large table. pgstattuple_approx skips pages whose visibility map bit is set, because those are assumed to hold no dead tuples. Dead tuple counts stay exact, while live tuples and free space become estimates.

High dead_tuple_percent means vacuum is behind or something holds back cleanup. High free_percent means the file contains space that ordinary vacuum may not give back to the operating system.

Caveats: by default only members of the pg_stat_scan_tables role can execute these functions, besides superusers. The functions take a read lock only, so they don’t block reads or writes, but the docs say the result is not an instantaneous snapshot. The approximate version still scans the pages that are not all-visible, so it is cheaper, not free.

Further reading: pgstattuple

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; pg_dump -O -x -f mydb.sql mydb FROM pg_stat_user_indexes All Postgresql tips (24) All topics

Link