PostgreSQL索引优化

时间:2012-10-20 15:11:57

标签: postgresql postgresql-performance

目前我对以下SQL Select语句有以下几点。然而,对我来说查询似乎仍然很慢(10.000条记录)。你有什么建议吗?

  1. index category_id
  2. index delivery_date
  3. product_id,product_name
  4. 上的索引

    这是我的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 ANALYZE的输出下面:

    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
    

1 个答案:

答案 0 :(得分:1)

查询的绝对理想配置是(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相同的结果。