有几个很好的帖子,例如:
显示如果您在列 (A,B) 上有复合索引,并且在 (A) 上有单个索引,postgres 将使用复合索引(以改进缓存),而单个索引是多余的,可以删除。
在测试时,我注意到当复合可用时,postgres 有时会使用单个索引,但我不知道这是否意味着我们仍然需要(为了查询性能)两个索引。
考虑以下:
CREATE TABLE public.events (
id serial4 NOT NULL,
reference int4 NOT NULL,
"name" varchar(255) NULL,
bet_source varchar NULL,
CONSTRAINT events_pkey PRIMARY KEY (id),
CONSTRAINT events_reference_betsource_key UNIQUE (reference, bet_source)
);
CREATE INDEX event_reference ON public.events USING btree (reference);
这里的细微差别是复合索引是唯一的,并且被声明为约束(我假设与创建唯一索引相同)
explain (analyze, buffers)
select * from events e where e.reference = 123;
Index Scan using event_reference on events e (cost=0.28..8.30 rows=1 width=51) (actual time=0.006..0.007 rows=0 loops=1)
Index Cond: (reference = 123)
Buffers: shared hit=2
Planning:
Buffers: shared hit=69 dirtied=1
Planning Time: 0.432 ms
Execution Time: 0.036 ms
从解释计划中我们可以看到postgres选择使用单一索引。通常当我在其他表上测试时,postgres 在这种情况下会选择复合索引。
问题是,
我可以安全地删除 event_reference 而不会影响查询性能吗?由于我无法访问生产数据(或其副本),因此用真实数据进行测试将很困难。
是与唯一索引相同的唯一约束(用于查询和插入优化)