@标签 PostgreSQL Database db SQL table size
参考文章:
查看单个数据库的存储空间占用
注意把 mydb
替换成你实际要查看的数据库的名字
SELECT pg_size_pretty( pg_database_size('mydb') );
据我实测,300GB 的数据库查询一次耗时不到一秒:
+------------------+
| pg_size_pretty |
|------------------|
| 325 GB |
+------------------+
SELECT 1
Time: 0.798s
查看单张表的存储空间占用
注意把 mytable
替换成你实际要查看的数据表的名字
SELECT pg_size_pretty( pg_total_relation_size('mytable') );
输出示例:
+------------------+
| pg_size_pretty |
|------------------|
| 1985 MB |
+------------------+
SELECT 1
Time: 0.254s
高级技巧
用 Python 依次输出数据库和当前数据库中每张表的存储空间占用
cur = db.execute_sql("SELECT pg_size_pretty( pg_database_size('mydb') );")
print("## Total database size: {}".format(cur.fetchone()[0]))
cur = db.execute_sql("SELECT tablename FROM pg_tables WHERE schemaname = 'public';")
for res in cur.fetchall():
tbl_name = res[0]
tsize = db.execute_sql(
"SELECT pg_size_pretty( pg_total_relation_size(%s));",
[tbl_name]
).fetchone()[0]
print("* {} size: {}".format(tbl_name, tsize))
输出示例:
## Total database size: 325 GB
* table_a size: 37 MB
* table_b size: 33 MB
* table_c size: 3928 kB
...