idx

btree & hash索引:
order by :
会使用索引(如果有索引)
对于limit...offset.....:
demo中两个SQL语句只是offset的值发生了变更,就导致查询的速度相差甚广。这是因为
此SQL语句中在对create_time进行使用btree索引扫描(因为有索引)的时候扫描的row太多。
扫描row太多的原因:
1:where 部分数据太多。
2:where 部分数据create_time字段的值在中太过分散。
3:如上文作者所说,执行计划基本一样(除了limit部分的cost部分)但是走索引扫描的记录却千差万别
如果想查看一个SQL语句扫描了多少row(explain verbose analyze),参见:

digoal=# explain verbose select * from aa order by a limit 10 offset 90; QUERY PLAN ------------------------------------------------------------------------------------- Limit (cost=3.64..4.01 rows=10 width=22) Output: a, b -> Index Scan using aa_pkey on public.aa (cost=0.28..112.30 rows=3001 width=22) Output: a, b (4 rows) digoal=# explain verbose select * from aa where a<2000 order by a limit 10 offset 90; QUERY PLAN ------------------------------------------------------------------------------------ Limit (cost=4.15..4.58 rows=10 width=22) Output: a, b -> Index Scan using aa_pkey on public.aa (cost=0.28..44.13 rows=1020 width=22) Output: a, b Index Cond: (aa.a < 2000) (5 rows)

 

digoal=# truncate table aa; TRUNCATE TABLE

digoal=# create index idx_b on aa(b); CREATE INDEX

digoal=# insert into aa select generate_series(1,1000),random(); INSERT 0 1000

digoal=# explain analyze select * from aa order by a limit 10 offset 90; QUERY PLAN ------------------------------------------------------------------------------------------------------ Limit (cost=3.64..4.01 rows=10 width=22) (actual time=0.083..0.089 rows=10 loops=1) -> Index Scan using aa_pkey on aa (cost=0.28..112.30 rows=3001 width=22) (actual time=0.034..0.076 rows=100 loops=1) Total runtime: 0.116 ms (3 rows)



 

posted @ 2014-05-30 10:34  bielidefeng  阅读(165)  评论(0编辑  收藏  举报