Sub topic 8
Finding out how big things are
This chapter assumes you can connect with psql, use meta-commands such as \dt and \d+, and read basic catalog queries. It covers how to measure databases, tables and indexes, which size function to use for each question, and where the numbers can mislead you.
Why size matters when exploring
Size tells you where the data lives. A table that holds 90% of a database is where slow queries, long backups and disk alerts usually start. Size is also a quick check on health. An index larger than its table, or a small table that takes gigabytes of disk, points to a problem worth investigating.
PostgreSQL measures size with built-in functions that return bytes as a bigint. You wrap the result in pg_size_pretty() to get a readable value such as 42 MB.
The size functions
Each function answers a different question. The names are similar, so the differences are easy to mix up.
| Function | What it measures |
|---|---|
| `pg_database_size(name or oid)` | The whole database on disk |
| `pg_relation_size(regclass)` | One fork of one relation, by default the main data (the heap for a table, the b-tree for an index) |
| `pg_table_size(regclass)` | Heap plus TOAST table plus free space map and visibility map. Excludes indexes |
| `pg_indexes_size(regclass)` | All indexes on a table |
| `pg_total_relation_size(regclass)` | `pg_table_size` plus `pg_indexes_size` |
| `pg_size_pretty(bigint)` | Formats a byte count as text |
TOAST (The Oversized-Attribute Storage Technique) is the mechanism PostgreSQL uses to store large column values, such as long text or JSON, in a separate hidden table. A table with big jsonb columns can have a small main heap and a large TOAST table. pg_relation_size would hide that cost, and pg_total_relation_size shows it.
Sizing databases
List every non-template database, largest first:
SELECT datname,
pg_size_pretty(pg_database_size(datname)) AS size
FROM pg_database
WHERE NOT datistemplate
ORDER BY pg_database_size(datname) DESC;In psql, \l+ prints the same information in a Size column, next to the tablespace and description. Calling pg_database_size on a database requires the CONNECT privilege on it (or membership in pg_read_all_stats), so a restricted role may get a permission error for some databases.
Sizing one table
To see where one table's space goes, call the functions side by side. The cast 'public.orders'::regclass turns a table name into an object identifier and respects the schema.
SELECT pg_size_pretty(pg_relation_size('public.orders')) AS heap,
pg_size_pretty(pg_table_size('public.orders')
- pg_relation_size('public.orders')) AS toast_and_maps,
pg_size_pretty(pg_indexes_size('public.orders')) AS indexes,
pg_size_pretty(pg_total_relation_size('public.orders')) AS total;The toast_and_maps column is a subtraction. It combines the TOAST table with the small free space and visibility map files, so it is only an approximation of TOAST alone. If it is large, the table stores big values.
In psql, \dt+ public.* lists tables with a Size column, and \di+ does the same for indexes. In recent versions the \dt+ Size column reports the table size, which excludes indexes. Use the SQL functions when you need the total.
Ranking the biggest tables
This is the query from the chapter's examples. It uses pg_class and pg_namespace to rank ordinary tables:
SELECT n.nspname AS schema_name,
c.relname AS table_name,
pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size
FROM pg_class c
JOIN pg_namespace 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;Two details matter here:
ORDER BYuses the raw byte value, not the pretty text. If you sorted by the output ofpg_size_pretty,9 MBwould sort after10 GBalphabetically.relkind = 'r'selects ordinary tables. Other kinds that have storage includem(materialized view),i(index) andt(TOAST table). Their sizes are already counted inside their parent table's total.
Partitioned tables
A partitioned parent table (relkind = 'p') has no storage of its own, so its own size is zero. Sum its partitions with pg_partition_tree:
SELECT pg_size_pretty(sum(pg_total_relation_size(relid))) AS total_size
FROM pg_partition_tree('public.measurements')
WHERE isleaf;Here public.measurements stands for any partitioned table in your database. The isleaf filter keeps only the partitions that hold data.
Ranking indexes
Indexes often outgrow expectations. This lists the indexes on one table, largest first:
SELECT indexrelid::regclass AS index_name,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_index
WHERE indrelid = 'public.orders'::regclass
ORDER BY pg_relation_size(indexrelid) DESC;An index that is large and never used is a candidate for removal. To check usage, look at idx_scan in pg_stat_user_indexes, which counts how many times each index has been scanned since statistics were last reset.
Counting rows without scanning
SELECT count(*) reads the whole table, which is slow on big tables. For a rough figure, read the planner's estimate instead:
SELECT reltuples::bigint AS estimated_rows
FROM pg_class
WHERE oid = 'public.orders'::regclass;reltuples is updated by VACUUM, ANALYZE and some index operations. In PostgreSQL 14 and later it is -1 for a table that has never been vacuumed or analyzed. In older versions it is 0. The estimate can also lag behind heavy inserts or deletes. A similar figure, n_live_tup, is in pg_stat_user_tables.
Gotchas
- Size on disk is not data size. Updates and deletes leave dead row versions behind until
VACUUMmarks the space reusable. A table can be much larger than its live data. Ordinary vacuum rarely returns space to the operating system, so the file stays large. - Compression changes the picture. TOAST values are compressed, so a large text column may take less space than its character count suggests.
- Sizes are a snapshot. Statistics views and
reltuplesupdate lazily, while the size functions read the current file sizes. - Temporary and unlogged tables. Temporary tables are visible only in the session that created them. Size functions work on them, but other sessions cannot see them.
Checking the work in pgAdmin
pgAdmin shows the same numbers without SQL. Select a table in the object browser and open its Statistics tab. It lists table size, indexes size and TOAST size, along with row counts and scan counters. Use it to confirm figures you computed in psql.
Exercise
A table shows pg_relation_size of 50 MB but pg_total_relation_size of 2 GB. Name two places the extra space could be, and which function would separate them.
Show answer
The extra space is in the indexes or in the TOAST table (or both). pg_indexes_size('tablename') returns the index portion, and pg_table_size('tablename') - pg_relation_size('tablename') returns TOAST plus the small free space and visibility maps. A table with large jsonb or text values points to TOAST. A table with many wide indexes points to indexes.
Exercise
Why does a query that orders tables by pg_size_pretty(pg_total_relation_size(c.oid)) return a wrong ranking?
Show answer
pg_size_pretty returns text, so the sort is alphabetical rather than numeric. For example, 9 MB sorts after 10 GB. Sort by pg_total_relation_size(c.oid) (the raw bytes) and apply pg_size_pretty only in the SELECT list.