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

使用pg_total_relation_size查询public模式表大小报错求助

修正PostgreSQL查询public模式表大小的错误

错误原因

pg_total_relation_size()函数要求接收regclass类型的参数(PostgreSQL内部的关系对象标识符),但information_schema.tables中的table_name是sql_identifier类型的字符串,直接传入会触发类型不匹配错误。同时,仅传递table_name可能因同名表导致识别错误,必须带上schema限定。

错误提示里的information_schema.sql_identifier是table_name字段的原生类型,和WHERE子句的过滤逻辑无关——即使已经筛选出public模式的表,字段类型不会改变,因此依然会触发类型错误。

修正后的查询语句

方法一:用format()拼接并转换类型

这种写法简洁且能安全处理特殊字符(如含空格、关键字的表名):

SELECT table_name, table_schema, table_catalog,
       pg_size_pretty(pg_total_relation_size(format('%I.%I', table_schema, table_name)::regclass)) as table_size
FROM information_schema.tables
WHERE table_schema = 'public';

方法二:用quote_ident()处理标识符

通过拼接带引号的schema和表名,避免特殊字符引发的语法问题:

SELECT table_name, table_schema, table_catalog,
       pg_size_pretty(pg_total_relation_size((quote_ident(table_schema) || '.' || quote_ident(table_name))::regclass)) as table_size
FROM information_schema.tables
WHERE table_schema = 'public';

方法三:直接查询系统表(效率更高)

跳过information_schema,直接查询PostgreSQL原生系统表pg_class和pg_namespace,性能更好:

SELECT 
    relname AS table_name,
    nspname AS table_schema,
    current_database() AS table_catalog,
    pg_size_pretty(pg_total_relation_size(c.oid)) AS table_size
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
WHERE 
    n.nspname = 'public'
    AND c.relkind = 'r'; -- 仅筛选普通表,排除视图、索引等对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:17:20