banner
李大仁博客

李大仁博客

天地虽大,但有一念向善,心存良知,虽凡夫俗子,皆可为圣贤。

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

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。