You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取PostgreSQL指定模式下所有表的总磁盘占用大小

获取PostgreSQL指定模式下所有表的磁盘占用大小

单表明细+排序(快速定位大表)

以下SQL会列出指定模式下所有用户表的详细占用情况,包含表本身、索引、TOAST存储的大小,并按总占用降序排列,方便快速找到占用空间最多的表:

SELECT
  schemaname AS "模式名",
  tablename AS "表名",
  pg_size_pretty(pg_total_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename))) AS "总占用空间",
  pg_size_pretty(pg_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename))) AS "表本身大小",
  pg_size_pretty(pg_indexes_size(quote_ident(schemaname) || '.' || quote_ident(tablename))) AS "索引大小",
  pg_size_pretty(pg_total_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename)) - pg_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename))) AS "索引+TOAST总大小"
FROM
  pg_stat_user_tables
WHERE
  schemaname = 'your_schema_name' -- 替换为目标模式名称
ORDER BY
  pg_total_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename)) DESC;

模式总占用统计

如果只需要获取指定模式下所有表的总磁盘占用,可以用聚合查询:

SELECT
  schemaname AS "模式名",
  pg_size_pretty(SUM(pg_total_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename)))) AS "模式总占用空间"
FROM
  pg_stat_user_tables
WHERE
  schemaname = 'your_schema_name' -- 替换为目标模式名称
GROUP BY
  schemaname;

关键函数说明

  • pg_total_relation_size():统计表、关联索引、TOAST存储的总磁盘占用,是最全面的空间统计方式
  • pg_size_pretty():将原始字节数转换为易读的格式(如KB/MB/GB)
  • quote_ident():自动处理包含特殊字符或关键字的模式/表名,避免SQL语法错误

内容的提问来源于stack exchange,提问作者justCurious

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 13:32:40