Sub topic 8
Finding Out How Big Things Are
Assume you know basic SQL, can connect with psql, and understand schemas, tables, indexes, and views. This chapter shows how to measure storage usage in PostgreSQL and identify objects that deserve attention.
What PostgreSQL Measures
A table's data is only one part of its storage. PostgreSQL may also store:
- Indexes used to find rows quickly.
- TOAST data, which stores oversized values such as long text.
- Free space and table metadata.
The main size functions are:
| Function | Includes |
|---|---|
| `pg_table_size` | Table data, TOAST data, and free space |
| `pg_indexes_size` | All indexes belonging to the table |
| `pg_total_relation_size` | The table, TOAST data, free space, and indexes |
pg_size_pretty converts a byte count into a readable value such as 128 MB.
Finding the Largest Tables
This query lists the ten largest ordinary tables outside PostgreSQL's system schemas:
SELECT n.nspname AS schema_name,
c.relname AS table_name,
pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size,
pg_size_pretty(pg_table_size(c.oid)) AS table_size,
pg_size_pretty(pg_indexes_size(c.oid)) AS index_size
FROM pg_class AS c
JOIN pg_namespace AS n
ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT 10;pg_class describes relations, including tables, indexes, and views. pg_namespace describes schemas. The relkind condition restricts the result to ordinary tables.
The oid column is PostgreSQL's internal identifier for an object. Passing it to the size functions avoids ambiguity when two schemas contain tables with the same name.
Using psql
In an interactive psql session, you can describe a table with:
\d+ public.ordersThe output includes the table's columns, indexes, and estimated storage information. To inspect several tables with a query, use the catalog query above.
You can also run the query from a file:
psql -X -d mydb -f table_sizes.sqlThe -X option prevents your personal psqlrc settings from changing the script's behavior.
Interpreting the Results
A large index_size can be normal for a table that supports many search patterns. It can also indicate duplicate or unused indexes. A large difference between table_size and the expected live data size may point to dead rows or bloat.
PostgreSQL reclaims space from deleted or updated rows through vacuuming. Regular vacuuming helps reuse space inside a table, but it does not always return that space to the operating system.
Exercise
Which function should you use when you want the full storage footprint of a table, including its indexes?
Show answer
Use pgtotalrelationsize(tableoid). Wrap it in pgsizepretty for readable units.