公开 · 所有人可见
查看PostgreSQL数据库中各表占据的存储空间
在PostgreSQL中,有几种方法可以查看数据库中各表占用的存储空间大小:
方法1:使用pg_total_relation_size函数
SELECT
table_schema,
table_name,
pg_size_pretty(pg_total_relation_size('"' || table_schema || '"."' || table_name || '"')) as size
FROM
information_schema.tables
WHERE
table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY
pg_total_relation_size('"' || table_schema || '"."' || table_name || '"') DESC;
方法2:使用pg_table_size和pg_indexes_size分别查看表和索引大小
SELECT
table_schema,
table_name,
pg_size_pretty(pg_table_size('"' || table_schema || '"."' || table_name || '"')) as table_size,
pg_size_pretty(pg_indexes_size('"' || table_schema || '"."' || table_name || '"')) as indexes_size,
pg_size_pretty(pg_total_relation_size('"' || table_schema || '"."' || table_name || '"')) as total_size
FROM
information_schema.tables
WHERE
table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY
pg_total_relation_size('"' || table_schema || '"."' || table_name || '"') DESC;
方法3:使用psql命令行工具的\dt+命令
在psql中连接到数据库后,执行:
\dt+ *.*
这会列出所有表及其大小信息。
方法4:查看特定表的大小
如果想查看特定表的大小:
SELECT pg_size_pretty(pg_total_relation_size('schema_name.table_name'));
注意事项
pg_total_relation_size包括表数据、索引、TOAST数据等所有相关存储pg_table_size只包含表数据大小(不包括索引)pg_indexes_size只包含索引大小pg_size_pretty函数将字节数转换为易读的格式(如MB、GB)
以上查询可以帮助你快速识别数据库中占用空间最多的表。