postgresql list and order tables by size

前端 未结 9 1198
不思量自难忘°
不思量自难忘° 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:51

    I like following statement:

    SELECT 
      table_name, 
      pg_size_pretty( pg_total_relation_size(quote_ident(table_name))), 
      pg_total_relation_size(quote_ident(table_name))
    FROM 
      information_schema.tables
    WHERE 
      table_schema = 'public'
    ORDER BY 
      pg_total_relation_size(quote_ident(table_name)) DESC
    

    You can see total size in a pretty format, but it id ordered correctly too.

    0 讨论(0)
  • 2020-12-12 12:02
    select table_name, pg_relation_size(quote_ident(table_name))
    from information_schema.tables
    where table_schema = 'public'
    order by 2
    

    This shows you the size of all tables in the schema public if you have multiple schemas, you might want to use:

    select table_schema, table_name, pg_relation_size('"'||table_schema||'"."'||table_name||'"')
    from information_schema.tables
    order by 3
    

    SQLFiddle example: http://sqlfiddle.com/#!15/13157/3

    List of all object size functions in the manual.

    0 讨论(0)
  • 2020-12-12 12:03

    This will show you the schema name, table name, size pretty and size (needed for sort).

    SELECT
      schema_name,
      relname,
      pg_size_pretty(table_size) AS size,
      table_size
    
    FROM (
           SELECT
             pg_catalog.pg_namespace.nspname           AS schema_name,
             relname,
             pg_relation_size(pg_catalog.pg_class.oid) AS table_size
    
           FROM pg_catalog.pg_class
             JOIN pg_catalog.pg_namespace ON relnamespace = pg_catalog.pg_namespace.oid
         ) t
    WHERE schema_name NOT LIKE 'pg_%'
    ORDER BY table_size DESC;
    

    I build this based on the solutions from here list of schema with sizes (relative and absolute) in a PostgreSQL database

    0 讨论(0)
提交回复
热议问题