建立连接:
psql -h <xx.xx.xx.xx> -U <username> -p <port>
罗列数据库:
\l
SELECT datname FROM pg_database;
选择数据库:
\c test
罗列表:
\dt
罗列系统所有表:
select * from pg_tables;
查询表结构:
\d test_table
注意:类似于mysql里的\G展示,使用\x打开expand功能,就会切换展示方式,再次\x就是关闭expand功能。
查询各库的磁盘占用大小:
select datname, pg_size_pretty(pg_database_size(datname)) from pg_database;
查询索引的磁盘占用大小:
select indexrelname, pg_size_pretty(pg_relation_size(relid)) as size from pg_stat_user_indexes;
退出:
\q
查看表大小时的四种函数:
#关系数据大小(不包含TOAST等,也不包含索引)
select pg_size_pretty(pg_relation_size('test_table'));
#索引大小
select pg_size_pretty(pg_indexes_size('test_table'));
#表大小(包含relation,包含TOAST等,但不包含索引)
select pg_size_pretty(pg_table_size('test_table'));
#表的整个大小(表大小+索引大小)
select pg_size_pretty(pg_total_relation_size('test_table'));
这里的TOAST指的是超长变长字段的优化存储,有点类似文本库的概念。当一个表里的变长字段都特别长时,可能会导致pg_relation_size很小,而pg_table_size很大。
完整的同时查看表和索引占用磁盘大小,同时按字节数逆序排列的SQL:
SELECT
table_name,
pg_size_pretty(table_size) AS table_size,
pg_size_pretty(indexes_size) AS indexes_size,
pg_size_pretty(total_size) AS total_size
FROM (
SELECT
table_name,
pg_table_size(table_name) AS table_size,
pg_indexes_size(table_name) AS indexes_size,
pg_total_relation_size(table_name) AS total_size
FROM (
SELECT ('"' || table_schema || '"."' || table_name || '"') AS table_name
FROM information_schema.tables
) AS all_tables
ORDER BY total_size DESC
) AS pretty_sizes;