查询 PG 表的大小通常需要使用函数/视图来实现,分为单独查询和批量查询的场景,下面简单列一下:
1. 单表大小查询
如果要查询单个表的大小,可以使用常用的函数,参考语句如下:
select pg_size_pretty(pg_relation_size('表名'));
注意:这个查询结果不包括索引大小,如果要查询索引大小,可以通过查询 information_schema.tables 来获取
2.所有数据库表大小批量查询
如果要查询所有表的大小,包括索引,那么最方便的就是直接查询 information_schema.tables 表了,可以参考如下查询语句:
select
table_name,
pg_size_pretty(table_size) as table_size,
pg_size_pretty(indexes_size) as indexes_size,
pg_size_pretty(total_size) as total_size
from
(
select
table_name,
pg_table_size(table_name) as table_size,
pg_indexes_size(table_name) as indexes_size,
pg_total_relation_size(table_name) as total_size
from
(
select
('"' || table_schema || '"."' || table_name || '"') as table_name
from
information_schema.tables
) as all_tables
order by
total_size desc
) as pretty_sizes;
End~