PostgreSQL 索引
创建索引
- index_name:索引名
- schema_name:
- tb_name:表名
- column_name: 表字段名
1.创建单个索引
CREATE INDEX index_name ON schema_name.tb_name USING btree (column_name)
2.创建联合索引
CREATE INDEX index_name ON schema_name.tb_name USING btree (column_name1, column_name2, column_name3)
查询索引
pg_indexes 表存放索引定义
- schemaname
- tablename
- indexname
- tablespace
- indexdef
pg_statio_all_indexes 表存放索引定义
- schemaname
- relname : 表名
- indexrelname : 索引名
- idx_blks_read
- idx_blks_hit
pg_stat_user_indexes 存放索引详细信息的表
- schemaname
- relname : 表名
- indexrelname : 索引名
- idx_scan
- idx_tup_read
- idx_tup_fetch
1.查询schema_public的索引
select * from pg_indexes where schemaname = 'public';
2.查询表tb_name的索引
select * from pg_indexes where tablename='tb_name';
3.查询表tb_name的索引
select * from pg_statio_all_indexes where relname='tb_name';
4. 查询所有表的索引使用情况
select * from pg_stat_user_indexes order by relname, idx_scan asc, idx_tup_read asc, idx_tup_fetch asc;
5. 查询表tb_name索引使用情况
select indexrelname,idx_scan,idx_tup_read,idx_tup_fetch from pg_stat_user_indexes where relname='tb_name';
6. 查询索引index_name使用情况
select idx_scan from pg_stat_user_indexes where indexrelname = 'index_name';
删除索引
DROP INDEX index_name
联合索引
有联合索引如下
CREATE INDEX index_name ON schema_name.tb_name USING btree (column_name1, column_name2, column_name3)
有单个索引如下
CREATE INDEX index_name_cloumn2 ON schema_name.tb_name USING btree (column_name2)
那么以下两种情况,
会使用联合索引 index_name
select * from tb_name where column_name1 = '' and column_name2 = '';
会使用联合索引 index_name 和 单个索引 index_name_cloumn2
select * from tb_name where column_name1 = '' and column_name2 <= '' and column_name2 >= '';