postgresql list and order tables by size

前端 未结 9 1212
不思量自难忘°
不思量自难忘° 2020-12-12 11:16

How can I list all the tables of a PostgreSQL database and order them by size?

9条回答
  •  长情又很酷
    2020-12-12 11:50

    This will be more clear.

    pg_size_pretty() - converts no.of bytes to human-readable format.

    pg_database_size() - gets database size in bytes.

    pg_total_relation_size() - gets total size of table and its index in bytes.

    pg_relation_size() - gets relation (table/index) size in bytes.

    pg_index_size() - gets index size of the relation in bytes.

    current_database() - gets the currently used database on which this query is being performed.

    Query:

    select current_database() as database,
           pg_size_pretty(total_database_size) as total_database_size,
           schema_name,
           table_name,
           pg_size_pretty(total_table_size) as total_table_size,
           pg_size_pretty(table_size) as table_size,
           pg_size_pretty(index_size) as index_size
           from ( select table_name,
                    table_schema as schema_name,
                    pg_database_size(current_database()) as total_database_size,
                    pg_total_relation_size(table_name) as total_table_size,
                    pg_relation_size(table_name) as table_size,
                    pg_indexes_size(table_name) as index_size
                    from information_schema.tables
                    where table_schema=current_schema() and table_name like 'table_%'
                    order by total_table_size
                ) as sizes;
    

    Result:

     database  | total_database_size | schema_name | table_name | total_table_size | table_size | index_size
    -----------+---------------------+-------------+------------+------------------+------------+------------
     vigneshdb | 1586 MB             | corpdata    | table_aaa  | 16 kB            | 0 bytes    | 8192 bytes
     vigneshdb | 1586 MB             | corpdata    | table_bbb  | 24 kB            | 0 bytes    | 16 kB
     vigneshdb | 1586 MB             | corpdata    | table_ccc  | 640 kB           | 112 kB     | 488 kB
     vigneshdb | 1586 MB             | corpdata    | table_ffffd  | 9760 kB          | 3152 kB    | 6568 kB
     vigneshdb | 1586 MB             | corpdata    | table_eee  | 1120 MB          | 311 MB     | 808 MB
    

    The humanized format is represent in bytes, kB, MB, GB, and TB.

    bytes to kB - begins from 10240 bytes

    bytes to MB - begins from 10485248 bytes = 10239.5 kB ~ 10 MB

    bytes to GB - begins from 10736893952 bytes = 10239.5 MB ~ 10 BG

    bytes to TB - begins from 10994579406848 bytes = 10239.5 GB ~ 10 TB

    All unit conversions starts from 10 + .

    For reference - Postgres Official Documentation

提交回复
热议问题