Index Scan

名称

索引扫描算子

介绍

顺序扫描的缺点就是无论表中的数据结构如何我们都要把所有的数据都拿一遍,即使我们为查询添加了一个选择率很小的条件,为了提高数据库的查询性能,提供了索引扫描算子。

索引扫描算子先扫描索引页面,根据条件快速定位数据在索引中的位置,从而直接拿到数据页面的数据,索引扫描在选择率比较小的条件上相比顺序扫描有比较大的性能提升。

获得一行数据后通过限定条件去判断是否满足,将满足的行进行投影操作,然后将投影后的数据返回。

举例

--创建环境
create table t1(a int,b int,c int);
create index idx1 on t1(a,b);

insert into t1 values(1,1,1);
insert into t1 values(1,1,2);
insert into t1 values(1,1,3);
insert into t1 values(1,2,1);

explain analyze select * from t1 where a = 1 and a + b = 2 and c = 1;
                                                        QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Index Scan using IDX1(Normal Index Scan) on T1  (cost=0.00..2.02 rows=1 width=12) (actual time=0.05..0.05 rows=1 loops=1)
   Index Key: (A = 1)
   Index Filter: ((A + B) = 2)
   Table Filter: (C = 1)
 Planning Time: 0.71 msec
 Execution Time: 0.16 msec
(6 rows)
  • using IDX1 算子属性,表示索引扫描使用的索引
  • Normal Index Scan 算子属性,表示索引扫描类型
  • on T1 算子属性,表示索引扫描的目标表
  • Index Key 索引扫描键,用来在索引页面进行二分查找
  • Index Filter 限定条件,拿到索引页面后进行计算
  • Table Filter 限定条件,拿到数据页面后进行计算

注解

  • 如果条件存在Index Key,则可以用来在索引页面做二分查找,快速定位,但是如果只有Index Filter,就没法快速定位,需要把索引数据都扫一遍,所以有没有index key对索引扫描的性能还是有很大影响的。
  • 扫描算子一定位于算子树的底部节点,所以不存在子算子

类型

--Normal Index Scan
create table t1(a int,b int,c int);
create index idx1 on t1(a);

explain analyze select a,b,c from t1 where a = 1;
                                                         QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------
 Index Scan using IDX1(Normal Index Scan) on T1  (cost=0.00..9.41 rows=41 width=12) (actual time=0.02..0.02 rows=0 loops=1)
   Index Key: (A = 1)
 Planning Time: 0.46 msec
 Execution Time: 0.07 msec
(4 rows)

Normal Index Scan 普通索引扫描,既要扫描索引页面,又要获取数据页面,见上述用例,通过条件A = 1来扫描索引,因为投影列除了A列以外还需要B列和C列,所以还需要拿到数据页面

--Fast Index Scan
create table t1(a int,b int,c int);
create index idx1 on t1(a);

SQL> explain analyze select a from t1 where a = 1;
                                                       QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------
 Index Scan using IDX1(Fast Index Scan) on T1  (cost=0.00..1.41 rows=41 width=4) (actual time=0.04..0.04 rows=0 loops=1)
   Index Key: (A = 1)
 Planning Time: 0.44 msec
 Execution Time: 0.07 msec
(4 rows)

Fast Index Scan 快速索引扫描,只需要扫描索引页面,不用获取数据页面,见上述用例,同样通过条件A = 1来扫描索引,但是投影列只需要A列,就不需要再去拿数据页面中的B列和C列了

注解

  • 如果where条件中存在除了索引列以外的列,也是不能走快速索引扫描的,即只有目标列和where条件中都的所有列都在索引上,才可以走快速索引扫描。