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

PGSQL查询所有表及大小报错:子查询返回多行问题排查

问题原因与解决方法

错误根源

你遇到的ERROR: more than one row returned by a subquery used as an expression错误,核心原因有两个:

  • 子查询SELECT datname FROM pg_database order by datname会返回所有数据库的名称(多行结果),但=运算符要求右侧必须是单个值,无法匹配多行,因此触发报错。
  • 逻辑错误:table_schema指的是数据库内的模式(Schema)(比如默认的public),而pg_database.datname是数据库名称,两者属于完全不同的层级,用它们做相等匹配本身逻辑就不成立。

正确的SQL写法

如果你想查询当前连接数据库中所有表的大小,可以用以下两种常用写法:

写法1:基于information_schema查询

SELECT 
    table_schema || '.' || table_name AS full_table_name,
    pg_relation_size(quote_ident(table_schema) || '.' || quote_ident(table_name)) AS table_size_bytes
FROM information_schema.tables
WHERE table_type = 'BASE TABLE' -- 仅查询普通表,排除视图等对象
AND table_schema NOT IN ('pg_catalog', 'information_schema'); -- 排除系统内置模式

写法2:基于pg_catalog系统表查询(更高效)

SELECT 
    schemaname || '.' || tablename AS full_table_name,
    pg_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename)) AS table_size_bytes,
    pg_size_pretty(pg_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename))) AS table_size_pretty -- 格式化显示大小(如KB/MB/GB)
FROM pg_catalog.pg_tables
WHERE schemaname NOT IN ('pg_catalog', 'information_schema');

补充说明

  • pg_relation_size()返回的是表的原始存储大小(单位字节),搭配pg_size_pretty()可以将其转换为更易读的格式。
  • 如果要查询特定模式下的表,只需添加AND table_schema = '你的模式名'(写法1)或AND schemaname = '你的模式名'(写法2)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:36:10