Postges使Seq-Scan而不是IndexOnly扫描非常简单的SELECT x..按x订购



我在Postgres 10中有一个表union_events,其中有17M行和102列。我运行命令:

CREATE INDEX union_events_index ON temp_schema_to_delete.union_events(id)
ANALYZE temp_schema_to_delete.union_events
EXPLAIN SELECT id FROM temp_schema_to_delete.union_events ORDER BY id

并得到以下结果:

Sort  (cost=3614290.72..3658708.19 rows=17766988 width=4)
Sort Key: id
->  Seq Scan on union_events  (cost=0.00..1474905.88 rows=17766988 width=4)

id是一个非空的、非唯一的整数字段。

我希望我的索引会被使用,我不必再对表进行排序了。

我做了一个快速测试:

SELECT s INTO temp_schema_to_delete.test FROM generate_series(0, 10000000) AS s
CREATE INDEX test_index ON temp_schema_to_delete.test(s)
ANALYZE temp_schema_to_delete.test
EXPLAIN SELECT s FROM temp_schema_to_delete.test ORDER BY s

它得到:

Index Only Scan using test_index on test  (cost=0.43..303940.15 rows=10000048 width=4)

看起来还好。

我的第一个表或查询出了什么问题?为什么不使用id上的索引?

根据@joop的建议,我为该表制作了一个VACUUM。

它产生了一个使用我的索引的更好的计划。

对我来说,仍然不清楚VACUUM如何帮助我重新解释我使用SELECT创建这个表的事实。。。INTO表,尚未进行任何更新或删除。

如果有人能在另一个答案中解释这一点,那就太好了,也许有一些有效的解决方案,然后真空。

最新更新