How to See the Size of a Database in PostgreSQL

Updated: January 4, 2024 By: Guest Contributor Post a comment

Introduction

When managing PostgreSQL databases, it’s often necessary to monitor their size for performance tuning, capacity planning, and to optimize resource allocation. This tutorial provides a step-by-step approach to determining the size of a database using PostgreSQL’s built-in functions and various advanced techniques tailored for different use cases.

Monitoring Database Size

Keeping track of the size of your PostgreSQL database is important for many reasons; it can help with forecasting storage needs, maintaining performance, and ensuring that adequate disk space is available. PostgreSQL provides several ways to get this data, which we’ll explore in detail.

Using pg_database_size()

One of the most straightforward methods to find out the size of a PostgreSQL database is using the pg_database_size() function:

SELECT pg_size_pretty(pg_database_size('your_database_name')) AS db_size;

This query will return the size of the specified database in a human-readable format.

Examining All Databases

If you want to see the size of all databases on the current PostgreSQL server, you can execute the following query:

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

This will give you a list of all databases and their respective sizes.

Advanced Techniques

Table Sizes Within a Database

Sometimes, seeing the size of individual tables within a database can be as insightful as the database size itself. To check the table sizes you can use:

SELECT relname AS table_name,
       pg_size_pretty(pg_total_relation_size(relid)) AS size
  FROM pg_catalog.pg_statio_user_tables
 ORDER BY pg_total_relation_size(relid) DESC;

This will provide a list of tables and their sizes in descending order.

Disk Usage by Specific Schema

In a multi-tenant database environment, you might need to know the size of a particular schema. Use the following query:

SELECT schema_name,
       pg_size_pretty(sum(table_size)) AS schema_size
  FROM (
    SELECT pg_catalog.pg_namespace.nspname as schema_name,
           pg_relation_size(pg_catalog.pg_class.oid) as table_size
      FROM   pg_catalog.pg_class
             JOIN pg_catalog.pg_namespace ON relnamespace = pg_catalog.pg_namespace.oid
  ) t
GROUP BY schema_name
ORDER BY schema_size DESC;

This will group the disk usage by schema and sort the result in descending order of size.

Understanding the Results

The values returned are typically in bytes, and the pg_size_pretty() function is used to convert them into a more easily digestible format such as MB, GB, or TB. However, it’s also crucial to understand what is included in this size – it encompasses the table data, indexes, and any additional overhead.

Automating Size Checks

Monitoring your PostgreSQL database size can also be automated using custom scripts that call the aforementioned functions and send alerts if the size exceeds certain thresholds.

Creating a Monitoring Script

Here’s an example of a basic script that could be created to monitor the size of a database:

// monitor_db_size.sh

DB_NAME='your_database_name'
MAX_SIZE='102400' // size in MB

CURRENT_SIZE=$(psql -t -c "SELECT pg_database_size('$DB_NAME')/1024/1024;")

if [[ $CURRENT_SIZE -gt $MAX_SIZE ]]; then
  echo "Database size has exceeded the threshold." // add your alert system here
fi

Regularly executing this script as a cron job would ensure ongoing monitoring of your database size.

Integrating With Monitoring Tools

For more sophisticated monitoring, integrating with tools like Nagios, Zabbix, or Prometheus can provide real-time analysis, dashboard views, and historical data tracking for database sizes.

Usage with Nagios

In Nagios, one could use NRPE (Nagios Remote Plugin Executor) to execute a custom plugin that runs the database size queries and reports back to the Nagios monitoring system.

Usage with Zabbix

By using Zabbix’s custom parameters, you could set up a monitoring item that queries PostgreSQL for the database size data and triggers actions based on predefined conditions.

Usage with Prometheus

With Prometheus, you could use the PostgreSQL Exporter to expose database metrics and then configure Prometheus to scrape this data according to your defined schedule.

Optimization Considerations

Upon finding out that a database is too large, there are optimization strategies such as data indexing, archiving old data, and database partitioning that can help manage the size more effectively. Regularly monitoring database size can keep you ahead of any potential issues before they become problematic.

Summary

Known as one of the most powerful database management systems, PostgreSQL offers robust built-in functions for assessing database size. Using the techniques laid out in this tutorial, maintaining the health and efficiency of your PostgreSQL instance can be accomplished with greater efficacy. Monitoring database size should be part of any DBA’s routine tasks to ensure smooth operations and scalability.