有用的PostgreSQL查询和命令

--显示正在运行的查询(9.2之前)-- show running queries (pre 9.2) 
SELECT procpid, age(clock_timestamp(), query_start), usename, current_query 
FROM pg_stat_activity 
WHERE current_query != '<IDLE>' AND current_query NOT ILIKE '%pg_stat_activity%' 
ORDER BY query_start desc;

--显示运行查询(9.2)-- show running queries (9.2)
SELECT pid, age(clock_timestamp(), query_start), usename, query 
FROM pg_stat_activity 
WHERE query != '<IDLE>' AND query NOT ILIKE '%pg_stat_activity%' 
ORDER BY query_start desc;

--杀死运行查询-- kill running query
SELECT pg_cancel_backend(procpid);

--杀死空闲查询-- kill idle query
SELECT pg_terminate_backend(procpid);

--真空指令-- vacuum command
VACUUM (VERBOSE, ANALYZE);

--所有数据库用户-- all database users
select * from pg_stat_activity where current_query not like '<%';

--所有数据库及其大小-- all databases and their sizes
select * from pg_user;

--所有表及其大小,有/无索引-- all tables and their size, with/without indexes
select datname, pg_size_pretty(pg_database_size(datname))
from pg_database
order by pg_database_size(datname) desc;


--缓存命中率(不应低于0.99)-- cache hit rates (should not be less than 0.99)
SELECT sum(heap_blks_read) as heap_read, sum(heap_blks_hit)  as heap_hit, (sum(heap_blks_hit) - sum(heap_blks_read)) / sum(heap_blks_hit) as ratio
FROM pg_statio_user_tables;

--表索引使用率(不应低于0.99)-- table index usage rates (should not be less than 0.99)
SELECT relname, 100 * idx_scan / (seq_scan + idx_scan) percent_of_times_index_used, n_live_tup rows_in_table
FROM pg_stat_user_tables 
ORDER BY n_live_tup DESC;

--缓存中有多少索引-- how many indexes are in cache
SELECT sum(idx_blks_read) as idx_read, sum(idx_blks_hit)  as idx_hit, (sum(idx_blks_hit) - sum(idx_blks_read)) / sum(idx_blks_hit) as ratio
FROM pg_statio_user_indexes;

--将远程主机上的数据库备份(转储)到文件-- Dump database on remote host to file
$ pg_dump -U username -h hostname databasename > dump.sql

--将转储导入现有数据库-- Import dump into existing database
$ psql -d newdb -f dump.sql
0条评论 顺序楼层
请先登录再回复