PostgreSQL如何查询表大小(单独查询和批量查询)

来自:网络
时间:2024-03-31
阅读:
免费资源网 - https://freexyz.cn/

前言

查询 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;

附:查询数据库大小

-- 查询单个数据库大小
select pg_size_pretty(pg_database_size('postgres')) as size;
 
-- 查询所有数据库大小
select datname, pg_size_pretty (pg_database_size(datname)) AS size from pg_database;

总结 

免费资源网 - https://freexyz.cn/
返回顶部
顶部