2013-08-31 17 views
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'; 

作爲每documentation「部分索引可以在查詢中使用僅在該系統可以識別出查詢的WHERE條件在數學上意味着索引的謂詞」。

這是否意味着索引將會或不會被使用?

回答

3

你可以檢查,是的,它會被使用。我創建SQL撥弄着這樣的查詢,以檢查它:

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))