最初是想找postgresql数据库占用空间命令发现的这篇blog,发现其中提供的几
条命令很有用(但也有几条感觉是充数的=。=),于是就把它翻译过来了。另外这篇文章是09年的,所以里面的内容可能有点过时,我收集了原文中有用的评论放在了最后面。
现在有不少开源软件都在使用postgreSQL作为它们的数据库系统。但公司可能不会招一些全职的postgreSQL DBA来维护它(piglei: 在国内基本也找不到)。而会让一些比如说Oracle DBA、Linux系统管理员或者程序员去 维护。在这篇文章中我们会介绍15个无论是对psql老鸟还是DBA都非常实用的postgresql数据库命令。
1. 如何找到postgreSQL数据库中占空间最大的表?
$ /usr/local/pgsql/bin/psql test
Welcome to psql 8.3.7, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit
test=# SELECT relname, relpages FROM pg_class ORDER BY relpages DESC;
relname | relpages
-----------------------------------+----------
pg_proc | 50
pg_proc_proname_args_nsp_index | 40
pg_depend | 37
pg_attribute | 30
</div>
如果你只想要最大的那个表,可以用limit参数来限制结果的数量,就像这样:
# SELECT relname, relpages FROM pg_class ORDER BY relpages DESC limit 1;
relname | relpages
---------+----------
pg_proc | 50
(1 row)
</div>
1.relname - 关系名/表名
2.relpages - 关系页数(默认情况下一个页大小是8kb)
3.pg_class - 系统表, 维护着所有relations的详细信息
4.limit 1 - 限制返回结果只显示一行
2. 如何计算postgreSQL数据库所占用的硬盘大小?
pg_database_size 这个方法是专门用来查询数据库大小的,它返回的结果单位是字节(bytes)。:
# SELECT pg_database_size('geekdb');
pg_database_size
------------------
63287944
(1 row)</div>
如果你想要让结果更直观一点,那就使用**pg_size_pretty**方法,它可以把字节数转换成更友好易读的格式。
# SELECT pg_size_pretty(pg_database_size('geekdb'));
pg_size_pretty
----------------
60 MB
(1 row)</div>
3. 如何计算postgreSQL表所占用的硬盘大小?
下面这个命令查出来的表大小是包含索引和toasted data的,如果你对除去索引外仅仅是表占的大小感兴趣,可以 使用后面提供的那个命令。
# SELECT pg_size_pretty(pg_total_relation_size('big_table'));
pg_size_pretty
----------------
55 MB
(1 row)</div>
如何查询不含索引的postgreSQL表的大小?
使用**pg_relation_size**而不是**pg_total_relation_size**方法。
# SELECT pg_size_pretty(pg_relation_size('big_table'));
pg_size_pretty
----------------
38 MB
(1 row)</div>
4. 如何查看postgreSQL表的索引?
让我们看下面这个例子,注意如果你的表有索引的话,你会在命令输出内容的后面那部分找到一个标题 Indexes ,在这个例子中,pg_attribut表有两个btree类型的索引,默认情况下postgreSQL使用的索引类型都 是btree,因为它适用于绝大多数情况。
test=# \d pg_attribute
Table "pg_catalog.pg_attribute"
Column | Type | Modifiers
---------------+----------+-----------
attrelid | oid | not null
attname | name | not null
atttypid | oid | not null
attstattarget | integer | not null
attlen | smallint | not null
attnum | smallint | not null
attndims | integer | not null
attcacheoff | integer | not null
atttypmod | integer | not null
attbyval | boolean | not null
attstorage | "char" | not null
attalign | "char" | not null
attnotnull | boolean | not null
atthasdef | boolean | not null
attisdropped | boolean | not null
attislocal | boolean | not null
attinhcount | integer | not null
Indexes:
"pg_attribute_relid_attnam_index" UNIQUE, btree (attrelid, attname)
"pg_attribute_relid_attnum_index" UNIQUE, btree (attrelid, attnum)
</div>