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