PostgreSQL manualy change query execution plan to force using sort and sequential access instead of full scan

我与影子孤独终老i 提交于 2019-12-08 11:45:11

问题


I have simple query like this:

SELECT  *
FROM    t1
WHERE   f1 > 42
        AND f2 = 'foo'
        AND f3 = 'bar'
ORDER BY f4 DESC 
LIMIT 10 OFFSET 100;

I have index for field f4 (for other queries). Condition "f1 > 42 AND f2 = 'foo' AND f3 = 'bar'" is not representative and corresponds to 70% of records in table t1. It's about 2 000 000 records in table and it is growing up every day. Query plan explanation for this query shows using of seq scan by entire table and then performing ordering and limitation.

Is it possible to say Postgres to perform this query thus way:

  1. Iterate through reverse ordered rows by using index on field f4.
  2. For each row do comparison with condition f1 > 42 AND f2 = 'foo' AND f3 = 'bar' and take it if corresponded.
  3. If result set size greater than limit stop iterate.

回答1:


Here are the configurations for the query planner. You can manipulate them to change the query plan (For your case it can be simple SET enable_seqscan = off; for this query).

But before you change the planner configuration - check if statistics on this table are correct and collect them again if needed.




回答2:


As far as I understand the goal is not only to change execution plan manually but continue to get execution plans similar as on production. In this case game with optimizer definitions is not completely reliable. Taking into consideration that data is continuously growing I would like to recommend partitions implementation on production and development, that will stabilize execution plan. This will leave less possibilities to make mistake in execution plan generation. As an alternative table might be clustered periodically by index on f4. Unfortunately it's not enough information to recommend exactly partitioning strategy.



来源:https://stackoverflow.com/questions/18122115/postgresql-manualy-change-query-execution-plan-to-force-using-sort-and-sequentia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!