[Answered ]-PostgreSQL pg_database_size different from sum of pg_total_relation_size

2👍

✅

Your pg_total_relation_size query is excluding system tables that start with pg_. Those tables do still take up space.

The minimum possible (non-broken) database is around 7.2MB in my hands. So the numbers you give work out.

0👍

The documentation for pg_total_relation_size says that it includes the size of indexes with it, but that wasn’t the case with my database. That may have been because I created the indexes with an explicit name rather than anonymous indexes.

Here are some queries to help track down where space is going:

-- total database size on disk
select * from pg_size_pretty(pg_database_size('etlq'));

-- total sizes by schema
select nspname, pg_size_pretty(sum(pg_total_relation_size(C.oid)))
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
GROUP BY nspname;

-- total size by relation
select nspname, relname, pg_size_pretty(pg_total_relation_size(C.oid)), pg_total_relation_size(c.oid)
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE true
and pg_total_relation_size(C.oid) > 10 * 1024 * 1024 -- greater than 10MB
ORDER BY pg_total_relation_size(C.oid) DESC, nspname;

Leave a comment