Postgres 似乎总是使用顺序扫描,它可以使用部分索引来仅获取索引扫描。它仅在一个从句超过 100 个元素时发生。
鉴于下表:
create table foo(id bigint primary key, bar bigint);
insert into foo (id, bar)
select g.id, case when id % 1000 = 0 then id else null end
from generate_series(1, 10000000) AS g (id) ;
--Create partial index
create unique index ix_foo_bar on foo(bar) where bar is not null;
analyze foo;
Run Code Online (Sandbox Code Playgroud)
并给出以下带有大语句的查询:
explain analyze select count(*) from foo where bar in (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101);
Run Code Online (Sandbox Code Playgroud)
查询计划显示顺序扫描。它很慢,而且成本很高:
QUERY PLAN
------------------------------------
Finalize Aggregate (cost=612955.35..612955.36 rows=1 width=8) (actual time=254.605..254.605 rows=1 loops=1)
-> …
Run Code Online (Sandbox Code Playgroud)