Querying Database Object Sizes
In this step, you will connect to the PostgreSQL database and query the sizes of a table and its index. Understanding the size of your database objects is crucial for performance tuning and capacity planning.
First, open a terminal. To connect to the PostgreSQL server as the postgres user and access the mydatabase database, execute the following command:
sudo -u postgres psql mydatabase
You should see the psql prompt (mydatabase=#), indicating you are connected to the mydatabase database. All subsequent SQL commands in this lab should be run in this psql shell unless otherwise specified.
Now, let's determine the size of mytable. We will use the pg_size_pretty and pg_relation_size functions. pg_relation_size returns the size of a table in bytes, and pg_size_pretty formats it into a human-readable format (e.g., KB, MB).
Execute the following SQL query to get the size of mytable:
SELECT pg_size_pretty(pg_relation_size('mytable'));
You should see output similar to this, showing the disk space used by the table's data:
pg_size_pretty
----------------
56 kB
(1 row)
Next, check the size of the index idx_mytable_name that was created on the name column:
SELECT pg_size_pretty(pg_relation_size('idx_mytable_name'));
The output will show the space consumed by the index:
pg_size_pretty
----------------
48 kB
(1 row)
Finally, to get the total size of the table including all its indexes, use the pg_total_relation_size function:
SELECT pg_size_pretty(pg_total_relation_size('mytable'));
This output shows the combined size of the table and its index:
pg_size_pretty
----------------
176 kB
(1 row)