Ever wanted to figure out which tables in your PostreSQL database are taking up the most space on the disk? It’s pretty easy to find out if you know the magic query.
First, connect to psql in the terminal via a command like:
psql -U postgres
Next, connect to the database of interest:
Paste the following SELECT statement into terminal and press Enter:
1 2 3 4 5 6 7 8 9
SELECT nspname || '.' || relname AS "relation", pg_size_pretty(pg_total_relation_size(C.oid)) AS "total_size" FROM pg_class C LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace) WHERE nspname NOT IN ('pg_catalog', 'information_schema') AND C.relkind <> 'i' AND nspname !~ '^pg_toast' ORDER BY pg_total_relation_size(C.oid) DESC LIMIT 20;
We hope you found this article useful. If you see any mistakes, missing features or ways to improve it, please let us know in the comments below so we can update its contents. If you're willing to link to us, we would sincerely appreciate it!