Video in progress

What can you learn about table health from the `pg_stat_user_tables` view?

It gives counters for each table: how many seq scans and index scans there were, how many rows were inserted/updated, how many dead rows exist, when the last VACUUM and ANALYZE ran. It's the first place I look for missing indexes and autovacuum problems.

📖 Answer

The query I use often:

SELECT relname,
       seq_scan, seq_tup_read,
       idx_scan,
       n_live_tup, n_dead_tup,
       n_tup_upd, n_tup_hot_upd,
       last_autovacuum, last_autoanalyze
FROM pg_stat_user_tables
ORDER BY seq_tup_read DESC
LIMIT 15;

What I look for:

  • Lots of seq_scan on a big table. If seq_tup_read / seq_scan is in the millions, some query is reading the whole table, so an index is missing. Then I look for the guilty query in pg_stat_statements.
  • A large n_dead_tup and an old last_autovacuum. Autovacuum isn't keeping up, or something (a long transaction) is blocking it.
  • A low n_tup_hot_upd / n_tup_upd. On a heavily updated table there are few HOT updates: the columns being updated have an index, or the page has no room.
  • A very old last_autoanalyze. The statistics are stale, and the planner may be estimating wrongly.

The counters are cumulative, since the last reset. That's why I send them to monitoring (for example, Prometheus via postgres_exporter) and watch the rate (how much per hour); an absolute number says little.

For indexes there is the similar pg_stat_user_indexes, and for I/O pg_statio_user_tables.