50

textPostgres 9.1 中的表中有一个类型列。我想知道该列对所需磁盘空间的影响。它不需要精确,但我想知道该列是否负责数据库消耗的磁盘空间的 20%/30%/...。

我知道pg_relation_size,但它只在表级别运行。

我有许多具有相同架构的数据库。我转储了一个较小的列,并用 grep 剪切列并剪切并比较了纯文本转储的大小。但这不一定是实时数据库中空间需求的良好指标,而且对于大型数据库来说也更难做到这一点。

4

3 回答 3

75
select
    sum(pg_column_size(the_text_column)) as total_size,
    avg(pg_column_size(the_text_column)) as average_size,
    sum(pg_column_size(the_text_column)) * 100.0 / pg_relation_size('t') as percentage
from t;
于 2013-08-19T15:35:33.560 回答
33

对已接受的答案略有改进:漂亮地打印大小并使用 pg_total_relation_size 更准确。

select
    pg_size_pretty(sum(pg_column_size(column_name))) as total_size,
    pg_size_pretty(avg(pg_column_size(column_name))) as average_size,
    sum(pg_column_size(column_name)) * 100.0 / pg_total_relation_size('table_name') as percentage
from table_name;
于 2019-02-14T09:36:49.360 回答
7

如果您想要按大小排序的数据库中所有列的报告,那么这里是方法

BEGIN;
CREATE FUNCTION tc_column_size(table_name text, column_name text)
    RETURNS BIGINT AS
$$
    declare response BIGINT;
BEGIN
    EXECUTE 'select sum(pg_column_size(t."' || column_name || '")) from ' || table_name || ' t ' into response;
    return response;
END;
$$
    LANGUAGE plpgsql;

SELECT
    z.table_name,
    z.column_name,
    pg_size_pretty(z.size)
FROM (
    SELECT
        table_name,
        column_name,
        tc_column_size(table_name, column_name) size
    FROM
        information_schema.columns
    WHERE
        table_schema = 'public') AS z
WHERE
    size IS NOT NULL
    -- and z.table_name = 'my_table' -- <--- uncomment to filter a table
ORDER BY
    z.size DESC;

ROLLBACK; -- <--- You may not want to keep that function
于 2020-03-20T20:15:12.240 回答