2

鉴于此部分索引:

CREATE INDEX orders_id_created_at_index 
   ON orders(id) WHERE created_at < '2013-12-31';

这个查询会使用索引吗?

SELECT * 
FROM orders 
WHERE id = 123 AND created_at = '2013-10-12';

根据文档,“只有当系统可以识别查询的 WHERE 条件在数学上暗示索引的谓词时,才能在查询中使用部分索引”。

这是否意味着将使用或不会使用该索引?

4

1 回答 1

3

你可以检查一下,是的,它会被使用。我创建了 sql fiddle 以使用如下查询对其进行检查:

create table orders(id int, created_at date);

CREATE INDEX orders_id_created_at_index ON orders(id) WHERE created_at < '2013-12-31';

insert into orders
select
    (random()*500)::int, '2013-01-01'::date + ((random() * 200)::int || ' day')::interval
from generate_series(1, 10000) as g

SELECT * FROM orders WHERE id = 123 AND created_at = '2013-10-12';
SELECT * FROM orders WHERE id = 123 AND created_at = '2014-10-12';

sql fiddle demo

如果您检查这些查询的执行计划,您将看到第一个查询:

Bitmap Heap Scan on orders (cost=4.39..40.06 rows=1 width=8) Recheck Cond: ((id = 123) AND (created_at < '2013-12-31'::date)) Filter: (created_at = '2013-10-12'::date)
-> Bitmap Index Scan on orders_id_created_at_index (cost=0.00..4.39 rows=19 width=0) Index Cond: (id = 123)

对于第二个查询:

Seq Scan on orders (cost=0.00..195.00 rows=1 width=8) Filter: ((id = 123) AND (created_at = '2014-10-12'::date))
于 2013-08-31T17:20:59.240 回答