开始
所谓index only scan ,就是因为 建立 index时,所包含的字段集合,囊括了我们 查询语句中的字段,这样,提取出相应的 index ,就不必再次提取数据块了。
例子:
postgres=# \d gaotab;
Table "public.gaotab"
Column | Type | Modifiers
--------+-----------------------+-----------
id | integer |
name | character varying(20) |
deptno | integer |
age | integer |
postgres=# create index idx_id_dept on gaotab(id,deptno);
CREATE INDEX
postgres=# analyze gaotab;
ANALYZE
postgres=#
postgres=# explain select id,deptno from gaotab where id=200;
QUERY PLAN
-------------------------------------------------------------------------------
Index Only Scan using idx_id_dept on gaotab (cost=0.00..8.27 rows=1 width=8)
Index Cond: (id = 200)
(2 rows)
为了抵消cache 的影响,重新执行 explain analyze
postgres=# explain analyze select id,deptno from gaotab where id=200;
QUERY PLAN
--------------------------------------------------------------------------------
-------------------------------------------
Index Only Scan using idx_id_dept on gaotab (cost=0.00..8.27 rows=1 width=8) (
actual time=30.912..30.915 rows=1 loops=1)
Index Cond: (id = 200)
Heap Fetches: 1
Total runtime: 47.390 ms
(4 rows)
postgres=#
再看看查询中有 index 不包含的字段的情况:
postgres=# explain select id,name from gaotab where id=200;
QUERY PLAN
---------------------------------------------------------------------------
Index Scan using idx_id_dept on gaotab (cost=0.00..8.27 rows=1 width=10)
Index Cond: (id = 200)
(2 rows)
postgres=# explain analyze select id,name from gaotab where id=200;
QUERY PLAN
--------------------------------------------------------------------------------
---------------------------------------
Index Scan using idx_id_dept on gaotab (cost=0.00..8.27 rows=1 width=10) (actu
al time=47.043..47.044 rows=1 loops=1)
Index Cond: (id = 200)
Total runtime: 63.506 ms
(3 rows)
postgres=#
在这里,我们必须要注意的一点是:
如果是那种 带 where 条件的,如果 前面用了 explain ,后面又对同一条语句用 explain analyze 的话,就会受到缓存的影响。
这样就不够准确了。
例如:
postgres=# explain select id,deptno from gaotab where id=200;
QUERY PLAN
-------------------------------------------------------------------------------
Index Only Scan using idx_id_dept on gaotab (cost=0.00..8.27 rows=1 width=8)
Index Cond: (id = 200)
(2 rows)
postgres=# explain analyze select id,deptno from gaotab where id=200;
QUERY PLAN
--------------------------------------------------------------------------------
-----------------------------------------
Index Only Scan using idx_id_dept on gaotab (cost=0.00..8.27 rows=1 width=8) (
actual time=0.000..0.000 rows=1 loops=1)
Index Cond: (id = 200)
Heap Fetches: 1
Total runtime: 0.006 ms
(4 rows)
postgres=#
学习