如何列出PostgreSQL数据库的所有表并按大小排序?
当前回答
select table_name, pg_size_pretty(pg_total_relation_size(quote_ident(table_name)))
from information_schema.tables
where table_schema = 'public'
order by pg_total_relation_size(quote_ident(table_name));
Pg_total_relation_size将包括索引和表的大小。 如果只需要表大小,那么pg_relation_size就足够了。
其他回答
这可以很容易地从psql控制台完成。
表大小:\dt+ 数据库大小\l+ 索引大小:\di+
对于表大小,首先使用\c db_name连接数据库。
请注意:上面不会按OP要求的大小排序,但它仍然可以提供帮助。
您可以获得总关系大小和关系大小,这可能取决于您的表关系。 下面是如何获取数据库中的前100个表:
SELECT schemaname AS table_schema,
relname AS table_name,
PG_SIZE_PRETTY(PG_TOTAL_RELATION_SIZE(relid)) AS total_size,
PG_SIZE_PRETTY(PG_RELATION_SIZE(relid)) AS data_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,
PG_RELATION_SIZE(relid) DESC
LIMIT 100;
这里的大多数答案使用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 nspname || '.' || relname AS "relation",
pg_size_pretty(pg_total_relation_size(C.oid)) AS "total_size"
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname NOT IN ('pg_catalog', 'information_schema')
AND C.relkind <> 'i'
AND nspname !~ '^pg_toast'
ORDER BY pg_total_relation_size(C.oid) DESC
;
信贷: https://makandracards.com/makandra/52141-postgresql-how-to-show-table-sizes
如果你正在寻找一个总的分解,吐司和索引大小使用这个:
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