经常有人问如何一次性精确查询数据库中每个表的大小,这里写了个脚本方便大家使用。
1、如果使用的是图形化客户端,首先运行下面的语句,然后复制运行结果放新窗口中运行即可
SELECT CASE
WHEN t.row_total = 1 THEN
'select * from(' || REPLACE(sql_content, ' union all ', ') a order by 2 desc;')
WHEN t.row_total = t.row_seq THEN
REPLACE(sql_content, ' union all ', ') a order by 2 desc;')
WHEN t.row_seq = 1 THEN
'select * from(' || sql_content
ELSE
sql_content
END sql_content
FROM (SELECT COUNT(*) over() row_total,
row_number() over() row_seq,
'SELECT ''' || quote_ident(tablename) ||
''' 表名, count(*) 表行数,pg_size_pretty(pg_total_relation_size(''' ||
quote_ident(tablename) || '''::regclass)) 表总大小 from ' || quote_ident(tablename) ||
' union all ' sql_content
FROM pg_tables
WHERE schemaname = 'public') t
ORDER BY t.row_seq;
2、如果使用的是命令行,则可以使用管道,一键查看
psql -qAtX -d test -U joan -c "SELECT CASE
WHEN t.row_total = 1 THEN
'select * from(' || REPLACE(sql_content, ' union all ', ') a order by 2 desc;')
WHEN t.row_total = t.row_seq THEN
REPLACE(sql_content, ' union all ', ') a order by 2 desc;')
WHEN t.row_seq = 1 THEN
'select * from(' || sql_content
ELSE
sql_content
END sql_content
FROM (SELECT COUNT(*) over() row_total,
row_number() over() row_seq,
'SELECT ''' || quote_ident(tablename) ||
''' 表名, count(*) 表行数,pg_size_pretty(pg_total_relation_size(''' ||
quote_ident(tablename) || '''::regclass)) 表总大小 from ' || quote_ident(tablename) ||
' union all ' sql_content
FROM pg_tables
WHERE schemaname = 'public') t
ORDER BY t.row_seq;" | psql -d test -U joan -f -
说明:
- 以上以public模式为例,烦请修改为你需要的模式;
- 可以修改以上语句查询全库表大小;
最后修改时间:2019-12-25 10:51:01
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




