李大仁博客

PostgreSQL查询表和index占用空间大小

PostgreSQL查询表和index占用空间大小

PostgreSQL表和index占用空间大小信息存储在
information_schema.tables中
通过SQL可以查询到相应的统计数据

--查出单个表的大小
select pg_size_pretty(pg_relation_size('TABLENAME'));

查出表大小按大小含Index

-- 查出表大小按大小含Index
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,
SUBSTRING("table_name",1,10) as short_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
where all_tables.table_name like '%TABLENAME%'
ORDER BY total_size DESC
) AS pretty_sizes

对于分区表,需要利用分区表的前缀进行统计

-- 对于分区表,需要利用分区表的前缀进行统计
SELECT short_name,
pg_size_pretty(sum(table_size)) AS table_size,
pg_size_pretty(sum(indexes_size)) AS indexes_size,
pg_size_pretty(sum(total_size)) AS total_size
FROM
(
SELECT
table_name,
SUBSTRING("table_name",1,45) as short_name,  -- SUBSTRING方式进行分区表表名分组
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
where all_tables.table_name like '%TABLENAME_PREFIX%'  -- TABLENAME_PREFIX分区表前缀
) as size_table
GROUP BY short_name
Exit mobile version