How to Find PostgreSQL Database and Table Size Using SQL

Updated

PostgreSQL elephant logo

For one database, pg_database_size(); for every database in the cluster, join it to pg_database:

SELECT datname, pg_size_pretty(pg_database_size(datname)) AS size
FROM pg_database
ORDER BY pg_database_size(datname) DESC;

  datname   |  size
------------+---------
 hw_r6_demo | 68 MB
 hw_r6_size | 23 MB
 hw_r6_cons | 7782 kB
 template1  | 7694 kB
 postgres   | 7622 kB
 template0  | 7465 kB
(6 rows)

That works from any database in the cluster and needs no connection to the ones being measured. The interesting part is what happens when you drill into tables, because there are four size functions and three of them answer a question you probably did not ask.

The four functions, on one real table

The table below is 1,500 rows, each carrying a 9,000-byte column of random characters, so almost all of its bytes end up in TOAST — PostgreSQL’s out-of-line storage for values too big for a page. It has two indexes:

SELECT
  pg_size_pretty(pg_relation_size('attachments'))       AS pg_relation_size,
  pg_size_pretty(pg_table_size('attachments'))          AS pg_table_size,
  pg_size_pretty(pg_indexes_size('attachments'))        AS pg_indexes_size,
  pg_size_pretty(pg_total_relation_size('attachments')) AS pg_total_relation_size;

 pg_relation_size | pg_table_size | pg_indexes_size | pg_total_relation_size
------------------+---------------+-----------------+------------------------
 104 kB           | 15 MB         | 128 kB          | 15 MB
(1 row)
  • pg_relation_size — the main heap fork only: 104 kB. Not the table.
  • pg_table_size — heap plus TOAST plus the free space and visibility maps, but no indexes: 15 MB.
  • pg_indexes_size — all indexes on the table, nothing else: 128 kB.
  • pg_total_relation_size — table plus indexes. This is “how much disk does this table cost me”, and it is the one you want.

The relationship holds exactly, in bytes:

SELECT pg_table_size('attachments')          AS table_bytes,     -- 15720448
       pg_indexes_size('attachments')        AS index_bytes,     --   131072
       pg_total_relation_size('attachments') AS total_bytes,     -- 15851520
       pg_table_size('attachments') + pg_indexes_size('attachments')
         = pg_total_relation_size('attachments') AS sums_up;     --        t

pg_table_size does not include indexes, and on this table believing otherwise would have hidden 128 kB of index and reported the heap at 104 kB as if that were the table. The gap between 104 kB and 15 MB is TOAST:

SELECT pg_size_pretty(pg_relation_size('attachments', 'main')) AS main,
       pg_size_pretty(pg_relation_size('attachments', 'fsm'))  AS fsm,
       pg_size_pretty(pg_relation_size('attachments', 'vm'))   AS vm;

  main  |  fsm  |     vm
--------+-------+------------
 104 kB | 24 kB | 8192 bytes

The sizes on this page come from one run and will not repeat to the byte on yours, because the wide column is randomly generated and an index built after a bulk load packs tighter than one built before it. The relationships do hold on every run, such as table size plus index size equalling the total, and find-db-size-using-sql.sh asserts those against the same docs and attachments tables on a new cluster at a spare port, printing the figures it measured so you can compare.

Biggest tables in a database

SELECT c.oid::regclass AS relation,
       pg_size_pretty(pg_table_size(c.oid))          AS table_size,
       pg_size_pretty(pg_indexes_size(c.oid))        AS index_size,
       pg_size_pretty(pg_total_relation_size(c.oid)) AS total
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','m','p')                      -- table, matview, partitioned table
  AND n.nspname NOT IN ('pg_catalog','information_schema')
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT 10;

  relation   | table_size | index_size | total
-------------+------------+------------+--------
 attachments | 15 MB      | 128 kB     | 15 MB
 docs        | 520 kB     | 136 kB     | 656 kB
(2 rows)

Filtering on relkind matters. Include 'i' (indexes) or 't' (TOAST tables) and you double-count, because pg_total_relation_size already contains both. On this small database, summing every relkind gives 43 MB against a real database size of 23 MB.

That query reads pg_class directly, so it reports every relation with storage regardless of your search_path. A table you know exists but cannot find in a listing is usually the other case: \dt shows only what is visible on the search path, which is why it can print Did not find any relations on a database that has them.

Per schema

This per-schema query cannot run:

SELECT schema_name, ... FROM information_schema.tables GROUP BY schema_name ...

ERROR:  column "schema_name" does not exist

The column is table_schema. Rather than fix the column name, use the catalog, which also lets you exclude views and foreign tables that have no storage:

SELECT n.nspname AS schema,
       pg_size_pretty(sum(pg_total_relation_size(c.oid))) AS total
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','m','p')
GROUP BY n.nspname
ORDER BY sum(pg_total_relation_size(c.oid)) DESC;

       schema       |  total
--------------------+---------
 public             | 16 MB
 pg_catalog         | 7880 kB
 information_schema | 248 kB
(3 rows)

Index sizes

This query returns table names labelled as index names. Run verbatim on this database:

SELECT relname AS index_name, pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes;

 index_name  | index_size
-------------+------------
 docs        | 64 kB
 docs        | 72 kB
 attachments | 48 kB
 attachments | 80 kB

In pg_stat_user_indexes, relname is the table and indexrelname is the index:

SELECT indexrelname AS index_name, relname AS on_table,
       pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
ORDER BY pg_relation_size(indexrelid) DESC;

      index_name      |  on_table   | index_size
----------------------+-------------+------------
 attachments_name_idx | attachments | 80 kB
 docs_title_idx       | docs        | 72 kB
 docs_pkey            | docs        | 64 kB
 attachments_pkey     | attachments | 48 kB
(4 rows)

pg_size_pretty switches units at 10, not at 1024

SELECT pg_size_pretty(x::bigint) FROM unnest(ARRAY[1024,10239,10240,1048576,10485759]) x;

 pg_size_pretty
----------------
 1024 bytes
 10239 bytes
 10 kB
 1024 kB
 10 MB

One megabyte prints as 1024 kB. That is not a bug, but it will break any script that parses the unit, and it is why comparisons and ORDER BY should always run on the raw bigint — as every query above does — with pg_size_pretty applied only to the column being displayed.

Why the parts never quite add up to the whole

SELECT pg_size_pretty(sum(pg_total_relation_size(c.oid))) AS sum_total_relation_size,
       pg_size_pretty(pg_database_size(current_database())) AS pg_database_size
FROM pg_class c WHERE c.relkind IN ('r','m','p','S');

 sum_total_relation_size | pg_database_size
-------------------------+------------------
 24 MB                   | 23 MB
(1 row)

pg_database_size measures the directory on disk; the per-relation sum measures relation forks. They will not match to the byte, and a small discrepancy is normal. If the gap is large, the usual causes are dead tuples not yet reclaimed by VACUUM and unlogged temporary files — neither of which any of these functions distinguishes from live data. If you need live-versus-dead, that is the pgstattuple extension, not these functions.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.