How to find the size of tables in a PostgreSQL database

How to find the size of tables in a PostgreSQL database
How to find the size of tables in a PostgreSQL database

When managing production databases, sooner or later the time will come when the available disk space will start to decrease dangerously. The crucial question then is which table is eating up the space. In this article we will see a ready-made, SQL query to instantly detect the size of the tables.

Unlike other databases, PostgreSQL does not have a ready-made graph to show you at a glance the size of a table, but it does have two functions: pg_relation_size and pg_total_relation_size that will help us find the information.

The SQL Query

The following script returns all the tables in your database, sorted from largest to smallest:

SELECT 
    schemaname AS schema_name,
    tablename AS table_name,
    pg_size_pretty(pg_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename))) AS table_size,
    pg_size_pretty(pg_total_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename))) AS total_size,
    ROUND(pg_total_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename)) / 1024.0 / 1024.0 / 1024.0, 4) AS total_size_gb
FROM pg_tables
WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
ORDER BY pg_total_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename)) DESC;
How to find the size of tables in a PostgreSQL database

What exactly is it calculating?

  1. table_size: Shows exclusively the space occupied by the table data itself.
  2. total_size: Indicates the real size of the table on disk. This includes the table, all indexes that are connected to it.
  3. total_size_gb: Gives the number to Gigabytes.

Bonus: How to find the total size of the Database

If, in addition to the tables, we want to see at a glance how much space the database we are in takes up in total, we can run:

SELECT 
    pg_database.datname AS database_name,
    pg_size_pretty(pg_database_size(pg_database.datname)) AS db_size
FROM pg_database
WHERE pg_database.datname = current_database();
How to find the size of tables in a PostgreSQL database

Sources:

Share it

Leave a reply