Use catalog views, size functions, and statistics views to measure PostgreSQL’s shared memory, per-session memory, and object sizes.
Memory usage covers shared buffers, work memory allocated to each sort/hash, maintenance memory for VACUUM, and the size of databases, tables, and indexes stored on disk.
Call pg_database_size(), pg_relation_size(), and pg_total_relation_size() for on-disk memory. Combine them with pg_size_pretty() to obtain a human-readable format.
Run SELECT pg_size_pretty(pg_database_size('ecommerce')); for the whole database. To inspect a single table such as Orders, use SELECT pg_size_pretty(pg_total_relation_size('Orders'));.
Query pg_stat_activity to list every backend, then join pg_stat_get_backend_memory_contexts(pid) on PostgreSQL 16+ or use OS tools (ps, top) with pg_backend_pid() for older versions.
Issue SHOW shared_buffers, work_mem, maintenance_work_mem, temp_buffers; to reveal the exact allocations the server will attempt to use.
Use EXPLAIN (ANALYZE, BUFFERS) SELECT ...; to display how many shared and local buffers were hit or read, indicating real memory pressure for a query.
Increase work_mem when many sorts spill to disk. Test with SET work_mem TO '64MB'; before running the query and measure temp file usage in pg_stat_statements.
Create a cron job that inserts pg_database_size() and pg_stat_database stats into a metrics table. Graph the series to detect sudden growth or memory exhaustion trends.
Yes. pg_database_size() sums all tables, indexes, and TOAST data in the database directory.
Session memory like work_mem is released at query end, but shared_buffers remain allocated to speed future reads until evicted.
PostgreSQL 16 introduces pg_stat_get_backend_memory_contexts(), giving per-context byte counts. Earlier versions need OS inspection.