postgresql 统计表大小

分享一个统计 postgresql 表大小的 sql

with table_size_in_bytes as (
    select table_schema
    , table_name
    , pg_size_pretty(pg_total_relation_size(table_schema||'.'||table_name)::bigint) 
        as size_in_humanreadable
    , pg_total_relation_size(table_schema||'.'||table_name) as size_in_byte
    from information_schema.tables 
)
(
    select 'ALL_SCHEMA' as table_schema
    , 'ALL_TABLE' as table_name
    , pg_size_pretty(sum(size_in_byte)::bigint) as size_in_humanreadable
    , sum(size_in_byte) as size_in_byte
    from 
    table_size_in_bytes
)
union all
(
    select table_schema
    , 'ALL_TABLE' as table_name
    , pg_size_pretty(sum(size_in_byte)::bigint) as size_in_humanreadable
    , sum(size_in_byte) as size_in_byte
    from 
    table_size_in_bytes
    group by table_schema
    order by sum(size_in_byte) desc
)
union all
(
    select table_schema
    , table_name
    , size_in_humanreadable
    , size_in_byte
    from 
    table_size_in_bytes
    order by size_in_byte desc
);

Leave a Reply

Your email address will not be published. Required fields are marked *