PostgreSQL 多查询条件,多个索引的选择算法与问题诊断方法

标签

PostgreSQL , 多列条件 , 多索引 , 单列索引 , 复合索引 , 联合索引 , 优化器 , 评估 , 行评估 , 成本


背景

当一个SQL中涉及多个条件,并且多个条件有多种索引可选时,数据库优化器是如何选择使用哪个索引的?

例如

有一张表,有2个字段,单列一个索引,双列一个复合索引.

建表。  
postgres=# create table tbl(id int, gid int);  
CREATE TABLE  
  
插入1000万记录,其中ID唯一,GID只有10个值。  
postgres=# insert into tbl select generate_series(1,10000000), random()*9 ;  
INSERT 0 10000000  
  
创建两个索引。  
postgres=# create index idx1 on tbl(id);  
CREATE INDEX  
postgres=# create index idx2 on tbl(gid,id);  
CREATE INDEX  

下面三条SQL,会如何选择使用哪个索引呢?

select * from tbl where id in (1,2,3,4,5,6,7,8,9,10) and gid=123;  
  
select * from tbl where id in (1,2,3,4,5,6,7,8,9,10) and gid=1;  
  
select * from tbl where id in (1,2,3,4,5,6,7,8,9,10);  

问题思考

人为选择

这三条QUERY,实际上有三重含义:

1、gid=123的行根本不存在。

如果让你来选索引,你肯定会选复合索引,马上就能定位到数据不存在扫描最少的BLOCK。

select * from tbl where id in (1,2,3,4,5,6,7,8,9,10) and gid=123;  

你可能感兴趣的:(数据库,c#)