如何列出PostgreSQL数据库的所有表并按大小排序?


当前回答

这将显示模式名、表名、size pretty和size(排序所需)。

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;

我基于PostgreSQL数据库中具有大小(相对大小和绝对大小)的模式列表的解决方案来构建它

其他回答

 select uv.a tablename, pg_size_pretty(uv.b) sizepretty 
 from (select tb.tablename a, pg_table_size('schemaname.'||tb.tablename::text) b 
        from pg_tables tb 
        where tb.schemaname ilike 'schemaname' 
        order by 2 desc
       ) uv
select table_name,n_live_tup, pg_size_pretty(pg_relation_size(table_name))
from information_schema.tables
inner join pg_stat_user_tables  on table_name=relname
where table_schema = 'public'
order by 2 desc

另一种替代方法

这将显示模式名、表名、size pretty和size(排序所需)。

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;

我基于PostgreSQL数据库中具有大小(相对大小和绝对大小)的模式列表的解决方案来构建它

select table_name, pg_size_pretty(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));

Pg_total_relation_size将包括索引和表的大小。 如果只需要表大小,那么pg_relation_size就足够了。

这可以很容易地从psql控制台完成。

表大小:\dt+ 数据库大小\l+ 索引大小:\di+

对于表大小,首先使用\c db_name连接数据库。

请注意:上面不会按OP要求的大小排序,但它仍然可以提供帮助。