Postgresql list and order tables by size
To quickly list and sort tables by size in PostgreSQL, use this command:
This will output the tables sorted from largest to smallest, including index size in the calculations.
Diving deeper: Dissecting table sizes
A comprehensive understanding of table size is crucial for efficient database management. Let's unpack it.
Table size: data vs index
For a closer look at your data and index sizes, we have our handy dandy pg_relation_size()
and pg_indexes_size()
functions:
Including TOAST tables in the mix
PostgreSQL utilizes "TOAST" (The Oversized-Attribute Storage Technique) tables to handle larger attribute values. To consider these in your total size accounting:
This includes TOAST tables and indexes!
Filtering by schema
Some PostgreSQL databases play host to multiple schemas. Here's how you can peer into a particular one:
Excluding system tables is as simple as avoiding schemas with the pg_
prefix.
Bulletproofing your queries
Finally, let's enhance your SQL toolkit by adding some protective measures and convenience features.
Prevent SQL injection and syntax issues
Using quote_ident()
helps mitigate SQL injection hazards and syntax issues:
Stay safe out there, folks; noir detectives teach us always to quote_ident()
your sources! 🔎
Query adjustments on-the-fly
To adapt your query to different environments, leverage current_schema()
and current_database()
. It's like having GPS for your skyline!
How's that for a personalized city tour?
Measure database coastline to coastline
pg_database_size()
gives you the size of an entire database. Talk about a birds-eye view!
Heads up: PostgreSQL's pretty-size notation switches units at 10+ (e.g., 10240 bytes becomes 10 kB).
Was this article helpful?