PSQL - Select size of tables for both partitioned and normal

帅比萌擦擦* 提交于 2020-01-17 04:54:51

问题


Thanks in advance for any help with this, it is highly appreciated.

So, basically, I have a Greenplum database and I am wanting to select the table size for the top 10 largest tables. This isn't a problem using the below:

select 
sotaidschemaname schema_name
,sotaidtablename table_name
,pg_size_pretty(sotaidtablesize) table_size
from gp_toolkit.gp_size_of_table_and_indexes_disk
order by 3 desc
limit 10
;

However I have several partitioned tables in my database and these show up with the above sql as all their 'child tables' split up into small fragments (though I know they accumalate to make the largest 2 tables). Is there a way of making a script that selects tables (partitioned or otherwise) and their total size?

Note: I'd be happy to include some sort of join where I specify the partitoned table-name specifically as there are only 2 partitioned tables. However, I would still need to take the top 10 (where I cannot assume the partitioned table(s) are up there) and I cannot specify any other table names since there are near a thousand of them.

Thanks again, Vinny.


回答1:


Your friends would be pg_relation_size() function for getting relation size and you would select pg_class, pg_namespace and pg_partition joining them together like this:

select  schemaname,
        tablename,
        sum(size_mb) as size_mb,
        sum(num_partitions) as num_partitions
    from (
        select  coalesce(p.schemaname, n.nspname) as schemaname,
                coalesce(p.tablename, c.relname) as tablename,
                1 as num_partitions,
                pg_relation_size(n.nspname || '.' || c.relname)/1000000. as size_mb
            from pg_class as c
                inner join pg_namespace as n on c.relnamespace = n.oid
                left join pg_partitions as p on c.relname = p.partitiontablename and n.nspname = p.partitionschemaname    
        ) as q
    group by 1, 2
    order by 3 desc
    limit 10;



回答2:


select * from 
(       
select schemaname,tablename, 
pg_relation_size(schemaname||'.'||tablename) as Size_In_Bytes 
from pg_tables 
where schemaname||'.'||tablename not in (select schemaname||'.'||partitiontablename from pg_partitions) 
and schemaname||'.'||tablename not in (select distinct schemaname||'.'||tablename from pg_partitions ) 

union all 

select schemaname,tablename, 
sum(pg_relation_size(schemaname||'.'||partitiontablename)) as Size_In_Bytes 
from pg_partitions
group by 1,2) as foo 

where Size_In_Bytes >= '0' order by 3 desc;


来源:https://stackoverflow.com/questions/32820312/psql-select-size-of-tables-for-both-partitioned-and-normal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!