I want to drop unused tables. I listed empty tables to make sure that tables not getting inserts and deletes (using such as temporary table) within 1 week.
Is there way for checking if a table is not getting any transactional operations?
I need a simple query to check this for a table.
2
Answers
Make a simple trigger function
activity_watch()
that monitors table activity into a log tableactivity
, addafter insert
,after delete
andafter update
triggers to your target tables and later inspect the log table. Here is an example for a target table calleddemo
.Drop the monitoring triggers after you no longer need them.
The
pg_stat_all_tables
and other system views track traffic on all your tables from the moment they get created. Based on those, you might be able to figure out when and how extensively they were used:All these somewhat translate to most recent table access. You can also see
pg_statio_all_tables
to determine how much stuff was written, read or removed.Files that physically hold those also have filesystem-level metadata you can check, or you could track them down in statement logs if you have that enabled, or you could even try to take a look at the WAL entries for those tables. All these are discussed here.
For those that aren’t empty you could guess based
xmin
/xmax
.If you have the logs, tracking triggers or
pgaudit
, it’s easiest to check there. If not, tracking down and inspecting individual files on the filesystem or in the WAL is a bit more inconvenient and harder to do in bulk but it’s the most reliable.