Skip to content

Instantly share code, notes, and snippets.

@hvanhonacker
Last active November 23, 2018 07:41
Show Gist options
  • Save hvanhonacker/0758e058bd66410e2cdd to your computer and use it in GitHub Desktop.
Save hvanhonacker/0758e058bd66410e2cdd to your computer and use it in GitHub Desktop.
Postgres - Disk Usage - Finding the largest databases in your cluster
-- Finding the largest databases in your cluster
SELECT d.datname AS Name, pg_catalog.pg_get_userbyid(d.datdba) AS Owner,
CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')
THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(d.datname))
ELSE 'No Access'
END AS Size
FROM pg_catalog.pg_database d
ORDER BY
CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')
THEN pg_catalog.pg_database_size(d.datname)
ELSE NULL
END DESC -- nulls first
LIMIT 20
-- Finding the total size of your biggest tables
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;
-- https://wiki.postgresql.org/wiki/Disk_Usage
@varunchandak
Copy link

Thanks for this. Can we get the output in KB/MB/GB only ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment