为什么在进行函数调用时不将索引用于tstarange字段?

时间:2019-07-06 20:11:40

标签: postgresql

在这种情况下,使用timestamp为常量索引时:

explain analyse select * from order_bt where '2019-03-01'::timestamptz <@ sys_period;
                                                                   QUERY PLAN             
------------------------------------------------------------------------------------------
 Index Scan using order_id_sys_period_app_period_excl on order_bt  (cost=0.15..8.17 rows=1
   Index Cond: ('2019-03-01 00:00:00+02'::timestamp with time zone <@ sys_period)
 Planning time: 0.185 ms
 Execution time: 0.085 ms
(4 rows)

但是当我调用返回timestamp索引的函数时,则不使用:

explain analyse select * from order_bt where sys_time() <@ sys_period;
                                                 QUERY PLAN                               
------------------------------------------------------------------------------------------
 Seq Scan on order_bt  (cost=0.00..1050.78 rows=19 width=136) (actual time=0.099..36.676 r
   Filter: (sys_time() <@ sys_period)
   Rows Removed by Filter: 927
 Planning time: 0.142 ms
 Execution time: 37.065 ms
(5 rows)

第二个查询的函数调用有什么问题? 如何解释PG使用索引?

1 个答案:

答案 0 :(得分:0)

Probably found

  

STABLE函数无法修改数据库,并且在给定单个语句内所有行的给定相同参数的情况下,保证返回相同的结果。该类别使优化器可以将函数的多个调用优化为单个调用。特别地,在索引扫描条件下使用包含此类函数的表达式是安全的。 (由于索引扫描只会评估比较值一次,而不是每行一次,因此在索引扫描条件下使用VOLATILE函数无效。

我的职能是volatile