4

I have tables that change a lot during the day, lots of data is deleted, modified and inserted.

I suspect that the tables and indexes on those tables might be bloated.

I've seen that there are extensions options for PostgreSQL that can check this, but I would like to avoid creating extensions in my database.

How can I get this information (table/index is bloated) without having to use PostgreSQL extensions (eg.:pgstattuple), using only native PostgreSQL 12 features.?

asked Nov 12, 2021 at 3:55
7
  • 1
    You cannot do that without pgstattuple. Why do people so often ask questions like "how can I do X without Y", where Y is the proper solution for X? Commented Nov 12, 2021 at 7:01
  • pgstattuple is a "built-in" extension and available in every Postgres installation (at least installable in the same way as Postgres itself) Commented Nov 12, 2021 at 8:10
  • See here or here or here or here Commented Nov 12, 2021 at 8:54
  • 1
    This might be of help. Commented Nov 12, 2021 at 9:07
  • 1
    @ALZ Yes, it scans the whole table. Commented Nov 4, 2024 at 12:28

1 Answer 1

8

As you have already been answered in the comments, it is best to use the standard pgstattuple extension. If you do not want to use it, for some reason, you can see the approximate bloat values as follows:

-- Perform ANALYZE on your table
ANALYZE <table_name>;
-- Get the number of deadlines in your tables.
select schemaname,
relname,
pg_size_pretty(pg_relation_size(schemaname|| '.' || relname)) as size,
n_live_tup,
n_dead_tup,
CASE WHEN n_live_tup > 0 THEN round((n_dead_tup::float / 
n_live_tup::float)::numeric, 4) END AS dead_tup_ratio,
last_autovacuum,
last_autoanalyze
from pg_stat_user_tables
order by dead_tup_ratio desc NULLS LAST;

The higher the dead_tup_ratio, the higher the bloat of your table. But these are approximate data collected in the course of collecting statistics! The best way to know for sure about bloat is to use the pgstattuple extension.

answered Nov 15, 2021 at 11:47
1
  • Shouldn't instead use the following formula to have the number of dead tuples above the total number of tuples: CASE WHEN n_live_tup > 0 THEN round((n_dead_tup::float / dn_live_tup::float+dn_dead_tup::float)::numeric, 4) END AS dead_tup_ratio, Commented Jan 18, 2023 at 14:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.