如何列出PostgreSQL数据库的所有表并按大小排序?
当前回答
select table_name,n_live_tup, pg_size_pretty(pg_relation_size(table_name))
from information_schema.tables
inner join pg_stat_user_tables on table_name=relname
where table_schema = 'public'
order by 2 desc
另一种替代方法
其他回答
这里的大多数答案使用pg_size_pretty,这是非常有用的,但如果你想输出一个数值,你可以自己计算
SELECT tab_size /1024 AS size_kb
,tab_size /1024 /1024 AS size_mb
,tab_size /1024 /1024 / 1024 AS size_gb
,tab_size /1024 /1024 / 1024 / 1024 AS size_tb
FROM
(
SELECT pg_total_relation_size(relid) AS tab_size
FROM pg_catalog.pg_statio_user_tables
WHERE schemaname = 'your_schema'
AND relname = 'your_table'
) AS tabs;
SELECT
relname as "Table",
pg_size_pretty(pg_total_relation_size(relid)) As "Size",
pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) as "External Size"
FROM pg_catalog.pg_statio_user_tables ORDER BY pg_total_relation_size(relid) DESC;
从这里截取https://wiki-bsse.ethz.ch/display/ITDOC/Check+size+of+tables+and+objects+in+PostgreSQL+database
select table_name,n_live_tup, pg_size_pretty(pg_relation_size(table_name))
from information_schema.tables
inner join pg_stat_user_tables on table_name=relname
where table_schema = 'public'
order by 2 desc
另一种替代方法
这可以很容易地从psql控制台完成。
表大小:\dt+ 数据库大小\l+ 索引大小:\di+
对于表大小,首先使用\c db_name连接数据库。
请注意:上面不会按OP要求的大小排序,但它仍然可以提供帮助。
如果你正在寻找一个总的分解,吐司和索引大小使用这个:
SELECT *, pg_size_pretty(total_bytes) AS total
, pg_size_pretty(index_bytes) AS INDEX
, pg_size_pretty(toast_bytes) AS toast
, pg_size_pretty(table_bytes) AS TABLE
FROM (
SELECT *, total_bytes-index_bytes-COALESCE(toast_bytes,0) AS table_bytes
FROM (
SELECT c.oid,nspname AS table_schema, relname AS TABLE_NAME
, c.reltuples AS row_estimate
, pg_total_relation_size(c.oid) AS total_bytes
, pg_indexes_size(c.oid) AS index_bytes
, pg_total_relation_size(reltoastrelid) AS toast_bytes
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE relkind = 'r'
) a
) a ORDER BY total_bytes DESC;
推荐文章
- SQL Server -事务回滚错误?
- 如何在SQL中有效地计数列值的发生?
- PostgreSQL列名区分大小写吗?
- 在WHERE子句中引用列别名
- 恢复未保存的SQL查询脚本
- 如果任何字段包含NULL, MySQL CONCAT将返回NULL
- 向临时表中插入数据
- postgresql COUNT(DISTINCT…)非常慢
- 无法绑定多部分标识符
- 为什么Oracle 9i将空字符串视为NULL?
- Postgres:检查数组字段是否包含值?
- 导入CSV文件到SQL Server中
- 如何在postgresql中创建数据库用户?
- NVL和Coalesce之间的Oracle差异
- 在SQL server查询中将NULL替换为0