小编典典

您如何找到 Postgres / PostgreSQL 表及其索引的磁盘大小

all

我从 Oracle 来到 Postgres,并寻找一种方法来查找表和索引大小bytes/MB/GB/etc,甚至更好地查找所有表的大小。在 Oracle
中,我有一个讨厌的长查询,它查看了 user_lobs 和 user_segments 以给出答案。

我假设在 Postgres 中有一些我可以在information_schema表格中使用的东西,但我没有看到在哪里。


阅读 75

收藏
2022-07-07

共1个答案

小编典典

试试数据库对象大小函数。一个例子:

SELECT pg_size_pretty(pg_total_relation_size('"<schema>"."<table>"'));

对于所有表格,大致如下:

SELECT
    table_schema || '.' || table_name AS table_full_name,
    pg_size_pretty(pg_total_relation_size('"' || table_schema || '"."' || table_name || '"')) AS size
FROM information_schema.tables
ORDER BY
    pg_total_relation_size('"' || table_schema || '"."' || table_name || '"') DESC;

编辑:为方便起见,这是@phord 提交的查询:

SELECT
    table_name,
    pg_size_pretty(table_size) AS table_size,
    pg_size_pretty(indexes_size) AS indexes_size,
    pg_size_pretty(total_size) AS total_size
FROM (
    SELECT
        table_name,
        pg_table_size(table_name) AS table_size,
        pg_indexes_size(table_name) AS indexes_size,
        pg_total_relation_size(table_name) AS total_size
    FROM (
        SELECT ('"' || table_schema || '"."' || table_name || '"') AS table_name
        FROM information_schema.tables
    ) AS all_tables
    ORDER BY total_size DESC
) AS pretty_sizes;

我已经稍微修改了它pg_table_size()以包含元数据并使大小相加。

2022-07-07