select usename, count(*) from pg_stat_activity group by usename;
复制代码
二、赋权操作
1、为指定用户赋予指定表的select权限
GRANT SELECT ON table_name TO username;
复制代码
2、修改数据库表所属的ownner
alter table table_name owner to username;
复制代码
3、授予指定用户指定表的所有权限
grant all privileges on table product to username;
复制代码
4、授予指定用户所有表的所有权限
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO username;
复制代码
三、数据库表或者索引
1、获取数据库表中的索引
select * from pg_indexes where tablename = 'product';
复制代码
2、获取当前db中所有表信息
select * from pg_tables;
复制代码
3、查询数据库安装了哪些扩展
select * from pg_extension;
复制代码
4、查询数据库中的所有表及其描述
select relname as TABLE_NAME ,col_description(c.oid, 0) as COMMENTS from pg_class c where relkind = 'r' and relname not like 'pg_%' and relname not like 'sql_%'
select * from pg_stat_statements order by total_time desc limit 5;
复制代码
备注:需要开启pg_stat_statements
复制代码
5、获取执行时间最慢的3条SQL,并给出CPU占用比例
SELECT substring(query, 1, 1000) AS short_query,
round(total_time::numeric, 2) AS total_time,
calls,
round((100 * total_time / sum(total_time::numeric) OVER ())::numeric, 2) AS percentage_cpu
FROM pg_stat_statements
ORDER BY total_time DESC
LIMIT 3;
复制代码
6、分析评估SQL执行情况
EXPLAIN ANALYZE SELECT * FROM product
复制代码
7、查看当前长时间执行却不结束的SQL
select datname, usename, client_addr, application_name, state, backend_start, xact_start, xact_stay, query_start, query_stay, replace(query, chr(10), ' ') as query from (select pgsa.datname as datname, pgsa.usename as usename, pgsa.client_addr client_addr, pgsa.application_name as application_name, pgsa.state as state, pgsa.backend_start as backend_start, pgsa.xact_start as xact_start, extract(epoch from (now() - pgsa.xact_start)) as xact_stay, pgsa.query_start as query_start, extract(epoch from (now() - pgsa.query_start)) as query_stay , pgsa.query as query from pg_stat_activity as pgsa where pgsa.state != 'idle' and pgsa.state != 'idle in transaction' and pgsa.state != 'idle in transaction (aborted)') idleconnections order by query_stay desc limit 5;
复制代码
8、查出使用表扫描最多的表
select * from pg_stat_user_tables where n_live_tup > 100000 and seq_scan > 0 order by seq_tup_read desc limit 10;
复制代码
9、查询读取buffer最多的5个SQL
select * from pg_stat_statements order by shared_blks_hit+shared_blks_read desc limit 5;
复制代码
10、获取数据库当前的回滚事务数以及死锁数
select datname,xact_rollback,deadlocks from pg_stat_database
复制代码
11、查询访问指定表的慢查询
select * from pg_stat_activity where query ilike '%<table_name>%' and query_start - now() > interval '10 seconds';