Search code examples
psqldatabase-partitioninggreenplum

PSQL - Select size of tables for both partitioned and normal


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.


Solution

  • 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;