0

在 postgres 中,我想知道生成计划所需的时间。我知道 \timing 给了我在找到最佳计划后执行计划的时间。但我想找出 postgres 找出最佳计划所需的时间。是否可以在 postgres 中确定这个时间。如果是,那么如何?

查询计划生成器有时也找不到最佳计划。我可以强制 postgres 使用最佳计划来生成计划吗?如果是,那我该怎么做?

4

1 回答 1

1

For the time taken to prepare a plan and the time taken to execute it, you can use explain (which merely finds a plan) vs explain analyze (which actually runs it) with \timing turned on:

test=# explain select * from test where val = 1 order by id limit 10;
                                   QUERY PLAN                                   
--------------------------------------------------------------------------------
 Limit  (cost=0.00..4.35 rows=10 width=8)
   ->  Index Scan using test_pkey on test  (cost=0.00..343.25 rows=789 width=8)
         Filter: (val = 1)
(3 rows)

Time: 0.759 ms
test=# explain analyze select * from test where val = 1 order by id limit 10;
                                                        QUERY PLAN                                                         
---------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.00..4.35 rows=10 width=8) (actual time=0.122..0.170 rows=10 loops=1)
   ->  Index Scan using test_pkey on test  (cost=0.00..343.25 rows=789 width=8) (actual time=0.121..0.165 rows=10 loops=1)
         Filter: (val = 1)
         Rows Removed by Filter: 67
 Total runtime: 0.204 ms
(5 rows)

Time: 1.019 ms

Note that there is a tiny overhead in both commands to actually output the plan.

Usually it happens e.g. in DB2 that since finding the optimal plan takes a lot of time..therefore the database engine decides to use a suboptimal plan...i think it must be the case with postgres also.

In Postgres, this only occurs if your query is gory enough that it cannot reasonably do an exhaustive search. When you reach the relevant thresholds (which are high, if your use-cases are typical), the planner uses the genetic query optimizer:

http://www.postgresql.org/docs/current/static/geqo-pg-intro.html

If it is then how can i fiddle with postgres such that it chooses the optimal plan.

In more general use cases, there are many things that you can fiddle, but be very wary of messing around with them (apart, perhaps, from collecting a bit more statistics on a select few columns using ALTER TABLE SET STATISTICS):

http://www.postgresql.org/docs/current/static/runtime-config-query.html

于 2013-10-19T11:41:12.013 回答