2012-10-20 128 views
1

当前我有下面的SQL Select语句的下列元素。尽管如此,查询似乎仍然很慢(10.000条记录)。你有什么建议?PostgreSQL索引优化

  1. 指数CATEGORY_ID
  2. 指数DELIVERY_DATE
  3. 上的product_id指数,PRODUCT_NAME

这里是我的DDL:

Create table product ( 
    product_id serial, 
    category_id int2, 
    product_name varchar(50), 
    delivery_date timestamp, 
    subtitle varchar(20), 
    price numeric(10,2), 
    retail_price numeric(10,2), 
    language_id int2, 
    store_id int2, 
    reseller_id int2  
); 

和SQL:

Select * 
from product 
WHERE delivery_date > '2012-10-20 06:00:00' AND category_id = 1 
ORDER BY product_id, product_name; 

任何帮助,将不胜感激。

下面的输出EXPLAIN分析一下:

Sort (cost=18.11..18.12 rows=1 width=119) (actual time=0.064..0.064 rows=0 loops=1) 
Sort Key: product_id, product_name 
Sort Method: quicksort Memory: 25kB 
    -> Seq Scan on product (cost=0.00..18.10 rows=1 width=119) (actual time=0.019..0.019 rows=0 loops=1) 
Filter: ((delivery_date > '2012-10-20 06:00:00'::timestamp without time zone) AND (category_id = 1)) 
Total runtime: 0.098 ms 
+3

编辑你的问题,并粘贴'explain analyze <你的选择语句>'的输出。 –

+3

请参阅http://stackoverflow.com/tags/postgresql-performance/info - 请显示Pg版本,'EXPLAIN(BUFFERS,ANALYZE)'输出等。 –

回答

0

您所查询的绝对理想的配置将是有复合索引(delivery_date, category_id, product_id)(category_id, delivery_date, product_id)

实际上,索引仅为(category_id, product_id)可能足以获得可接受的性能。

无论如何,EXPLAIN ANALYZE <original_query>是你最好的朋友。

还有一个注意事项:在您的查询中,ORDER BY product_id, product_name总是会得到与简单ORDER BY product_id相同的结果。

+0

谢谢您的回答。即使我不需要在查询中进行排序的product_name,为什么我们不需要将product_name添加到复合索引? – user1761691

+0

正是因为如此。如果由于某种原因,您决定不在查询中使用product_id(在ORDER BY或WHERE子句中),但使用了product_name,则应该在其中添加product_name的复合索引 – mvp

+0

因此,通常所说的复合索引应该包含所有“where”和“sort”子句的列? – user1761691