获取分区表的表大小(Postgres 10+)

时间:2019-02-28 07:56:40

标签: postgresql postgresql-10 postgresql-11

我在Postgres weekly上遇到了此查询,该查询以字节为单位显示表,表的大小,toast大小和索引大小:

SELECT
  relname AS table_name,
  pg_size_pretty(pg_total_relation_size(relid)) AS total,
  pg_size_pretty(pg_relation_size(relid)) AS internal,
  pg_size_pretty(pg_table_size(relid) - pg_relation_size(relid)) AS external,
  pg_size_pretty(pg_indexes_size(relid)) AS indexes
FROM pg_catalog.pg_statio_user_tables 
ORDER BY pg_total_relation_size(relid) DESC;

我知道Postgres正在为每个分区创建一个表,所以我要分别为每个分区获取条目,但是有没有一种方法可以使每个表获得一行,而不管该表是否已分区?

3 个答案:

答案 0 :(得分:1)

当然可以,但是您必须与其他目录表结合使用GROUP BY

  • 目录relkind中的属性pg_class将告诉您关系是否已分区(p)(r)。

    < / li>
  • 目录pg_inherits将告诉您哪个分区(inhrelid)属于哪个分区表(inhparent)。

由于可以再次对分区进行分区,因此,如果要覆盖所有基础,则必须编写一个递归公用表表达式。

答案 1 :(得分:1)

按照@Laurenz Albe的指示,我创建了一个满足我需要的查询。这将从特定数据库中获取所有分区表的总内存。

SELECT
   pi.inhparent::regclass AS parent_table_name, 
   pg_size_pretty(sum(pg_total_relation_size(psu.relid))) AS total,
   pg_size_pretty(sum(pg_relation_size(psu.relid))) AS internal,
   pg_size_pretty(sum(pg_table_size(psu.relid) - pg_relation_size(psu.relid))) AS external, -- toast
   pg_size_pretty(sum(pg_indexes_size(psu.relid))) AS indexes
FROM pg_catalog.pg_statio_user_tables psu
   JOIN pg_class pc ON psu.relname = pc.relname
   JOIN pg_database pd ON pc.relowner = pd.datdba
   JOIN pg_inherits pi ON pi.inhrelid = pc.oid
WHERE pd.datname = :database_name
GROUP BY pi.inhparent
ORDER BY sum(pg_total_relation_size(psu.relid)) DESC;

请注意,在有分区分区的情况下,根表不会有一行,但是每个父表都会有自己的行

答案 2 :(得分:0)

即使我们有多个分区级别,这也会给出每个父表的表大小:

WITH RECURSIVE tables AS (
  SELECT
    c.oid AS parent,
    c.oid AS relid,
    1     AS level
  FROM pg_catalog.pg_class c
  LEFT JOIN pg_catalog.pg_inherits AS i ON c.oid = i.inhrelid
    -- p = partitioned table, r = normal table
  WHERE c.relkind IN ('p', 'r')
    -- not having a parent table -> we only get the partition heads
    AND i.inhrelid IS NULL
  UNION ALL
  SELECT
    p.parent         AS parent,
    c.oid            AS relid,
    p.level + 1      AS level
  FROM tables AS p
  LEFT JOIN pg_catalog.pg_inherits AS i ON p.relid = i.inhparent
  LEFT JOIN pg_catalog.pg_class AS c ON c.oid = i.inhrelid AND c.relispartition
  WHERE c.oid IS NOT NULL
)
SELECT
  parent ::REGCLASS                                  AS table_name,
  array_agg(relid :: REGCLASS)                       AS all_partitions,
  pg_size_pretty(sum(pg_total_relation_size(relid))) AS pretty_total_size,
  sum(pg_total_relation_size(relid))                 AS total_size
FROM tables
GROUP BY parent
ORDER BY sum(pg_total_relation_size(relid)) DESC