Read amount on a postgres table

对着背影说爱祢 提交于 2021-01-05 07:43:10

问题


Is there any way to calculate the amount of read per second on a Postgres table?

but what I need is that whether a table has any read at the moment. (If no, then I can safely drop it)

Thank you


回答1:


To figure out if the table is used currently, tun

SELECT pid
FROM pg_locks
WHERE relation = 'mytable'::regclass;

That will return the process ID of all backends using it.

To measure whether s table is used at all or not, run this query:

SELECT seq_scan + idx_scan + n_tup_ins + n_tup_upd + n_tup_del
FROM pg_stat_user_tables
WHERE relname = 'mytable';

Then repeat the query in a day. If the numbers haven't changed, nobody has used the table.




回答2:


Audit SELECT activity

My suggestion is to wrap mytable in a view (called the_view_to_use_instead in the example) which invokes a logging function upon every select and then use the view for selecting from, i.e.

select <whatever you need> from the_view_to_use_instead ...

instead of

select <whatever you need> from mytable ...

So here it is

create table audit_log (table_name text, event_time timestamptz);

create function log_audit_event(tname text) returns void language sql as
$$
 insert into audit_log values (tname, now());
$$;

create view the_view_to_use_instead as
 select mytable.* 
 from mytable, log_audit_event('mytable') as ignored;

Every time someone queries the_view_to_use_instead an audit record with a timestamp appears in table audit_log. You can then examine it in order to find out whether and when mytable was selected from and make your decision. Function log_audit_event can be reused in other similar scenarios. The average number of selects per second over the last 24 hours would be

select count(*)::numeric/86400
 from audit_log
 where event_time > now() - interval '86400 seconds';


来源:https://stackoverflow.com/questions/65217314/read-amount-on-a-postgres-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!