PostgreSQL SQL收集
Contents
查看是否存在无效索引
SELECT * FROM pg_class, pg_index WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid;
查看大小
查看表大小:
\d+
查看数据库大小:
\l+
查看表,索引及总大小
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;
表访问统计
select schemaname,relname,seq_scan,idx_scan,cast(idx_scan as numeric) / (idx_scan + seq_scan)
as idx_scan_pct
from pg_stat_user_tables where (idx_scan +seq_scan) >0 order by idx_scan_pct;
表I/O统计
select relname,cast(heap_blks_hit as numeric) /(heap_blks_hit +heap_blks_read)
as hit_pct,heap_blks_hit,heap_blks_read from pg_statio_user_tables
where (heap_blks_hit + heap_blks_read) >0 order by hit_pct;
索引访问统计
select relname,cast(idx_blks_hit as numeric) /(idx_blks_hit + idx_blks_read )
as hit_pct,idx_blks_hit,idx_blks_read from pg_statio_user_tables
where (idx_blks_hit +idx_blks_read) >0 order by hit_pct;
索引I/O统计
select indexrelname,cast(idx_blks_hit as numeric) /( idx_blks_hit + idx_blks_read)
as hit_pct,idx_blks_hit,idx_blks_read from pg_statio_user_indexes
where (idx_blks_hit +idx_blks_read)>0 order by hit_pct ;
按索引访问次统计
select schemaname,relname,indexrelname,idx_scan,pg_size_pretty(pg_relation_size(i.indexrelid))
as index_size from pg_stat_user_indexes i join pg_index using (indexrelid)
where indisunique is false order by idx_scan,relname;
获取用户所属的schema
\dn+
常用 SQL 收集
insert on conflict
INSERT INTO tbl_Employee
VALUES (7,'Ramu')
ON CONFLICT (EmpID)
DO UPDATE SET EmpName = Excluded.EmpName;
-- 什么也不做
ON CONFLICT (EmpID) DO NOTHING;
索引相关操作
create [unique] index [CONCURRENTLY] [索引名, 如果不指定, 则由 pg 自动创建相应的名] on 表名 (列名 1, 列名 2);
drop index 索引名 [CASCADE];
copy
-- tsv 格式
copy hs300_pe from '/tmp/hs300.csv' DELIMITER E',';
-- csv 格式
copy hs300_pb from '/tmp/hs300.pb.csv' csv
备份/还原
pg_dump --host localhost --port 5432 --username postgres --format plain --ignore-version --verbose --file "<abstract_file_path>" --table public.tablename dbname
psql -U username -d database -1 -f your_dump.sql
免提示输入密码
PGPASSWORD=你的密码 psql -U postgres -c "select * from t limit 10;"