size3
Nice — that explains it. Your previous query listed every table (including partition children), so the parent rows looked wrong.
Below is a query that returns only top-level (parent) tables and aggregates the sizes of their partitions (plus the parent itself) — result shown in GB (rounded to 2 decimals):
WITH RECURSIVE descendants AS (
-- start from top-level tables (not a partition child)
SELECT c.oid AS parent_oid, c.oid AS child_oid
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','p') -- ordinary + partitioned tables
AND n.nspname NOT IN ('pg_catalog','information_schema')
AND NOT EXISTS (SELECT 1 FROM pg_inherits i WHERE i.inhrelid = c.oid)
UNION ALL
-- recurse to find all descendant partitions
SELECT d.parent_oid, c.oid AS child_oid
FROM descendants d
JOIN pg_inherits i ON i.inhparent = d.child_oid
JOIN pg_class c ON c.oid = i.inhrelid
)
SELECT
ns.nspname AS schema_name,
p.relname AS table_name,
ROUND(SUM(pg_total_relation_size(d.child_oid)) / 1024.0 / 1024.0 / 1024.0, 2) AS size_gb
FROM descendants d
JOIN pg_class p ON p.oid = d.parent_oid
JOIN pg_namespace ns ON ns.oid = p.relnamespace
GROUP BY ns.nspname, p.relname
ORDER BY SUM(pg_total_relation_size(d.child_oid)) DESC;
Quick notes:
- This returns only top-level tables (regular tables and partitioned parents). Partition children (individual partitions) are not listed separately.
- For non-partitioned tables the
size_gbis just that table's size. - The query uses a recursive walk of
pg_inheritsso it works for multi-level partition trees. - If you want to restrict to a single schema, add
AND ns.nspname = 'your_schema'in the first CTEWHEREclause. - Running
pg_total_relation_size()for many objects can be a bit heavy — expect the query to take some time on huge databases.
If you still see unexpected values, run this quick diagnostic (replace schema.parent_table):
SELECT
pg_size_pretty(pg_total_relation_size('schema.parent_table'::regclass)) AS parent_size,
pg_size_pretty(SUM(pg_total_relation_size(c.oid))) AS sum_of_partitions
FROM pg_inherits i
JOIN pg_class c ON c.oid = i.inhrelid
WHERE i.inhparent = 'schema.parent_table'::regclass;
Send me the output if the numbers still look off and I’ll help debug further.
Comments
Post a Comment