Check Size of a Table in PostgreSQL

To get an overview of how much space is taken by each table in a database.

psql --host=<host> --dbname=<dbname> --username=<username> --command='SELECT relname as "Table", pg_size_pretty(pg_total_relation_size(relid)) As "Size", pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) as "External Size" FROM pg_catalog.pg_statio_user_tables ORDER BY pg_total_relation_size(relid) DESC;'

The SQL above, in a prettier format looks like this:

SELECT
   relname as "Table",
   pg_size_pretty(pg_total_relation_size(relid)) As "Size",
   pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) as "External Size"
   FROM pg_catalog.pg_statio_user_tables ORDER BY pg_total_relation_size(relid) DESC;

Get the size of all objects:

psql --host=<host> --dbname=<dbname> --username=<username> --command='SELECT relname AS objectname, relkind AS objecttype, reltuples AS "#entries", pg_size_pretty(relpages::bigint*8*1024) AS size FROM pg_class WHERE relpages >= 8 ORDER BY relpages DESC;' > db_table_object_size.txt

Again, the SQL, in a prettier format:

SELECT
   relname AS objectname,
   relkind AS objecttype,
   reltuples AS "#entries", pg_size_pretty(relpages::bigint*8*1024) AS size
   FROM pg_class
   WHERE relpages >= 8
   ORDER BY relpages DESC;

About

I'm a technology professional who's been passionate about computers since my Grandad introduced me to an Intel 386 back in the 90s when I was a kid. Those moments inspired a passion within for technology, and I've been playing around with anything with a circuit board ever since. Whenever I have a moment you can probably find me working on something computer-related, and this is where I like to write about those moments.