title: Postgres query optimization (forcing an index scan)
body: <p>Below is my query. I am trying to get it to use an index scan, but it will only seq scan.</p>
  
  <p>By the way the <code>metric_data</code> table has 130 million rows. The <code>metrics</code> table has about 2000 rows.</p>
  
  <p><code>metric_data</code> table columns:</p>
  
  <pre><code>  metric_id integer
  , t timestamp
  , d double precision
  , PRIMARY KEY (metric_id, t)
  </code></pre>
  
  <p>How can I get this query to use my PRIMARY KEY index?</p>
  
  <pre><code>SELECT
      S.metric,
      D.t,
      D.d
  FROM metric_data D
  INNER JOIN metrics S
      ON S.id = D.metric_id
  WHERE S.NAME = ANY (ARRAY ['cpu', 'mem'])
    AND D.t BETWEEN '2012-02-05 00:00:00'::TIMESTAMP
                AND '2012-05-05 00:00:00'::TIMESTAMP;
  </code></pre>
  
  <p>EXPLAIN:</p>
  
  <pre><code>Hash Join  (cost=271.30..3866384.25 rows=294973 width=25)
    Hash Cond: (d.metric_id = s.id)
    -&gt;  Seq Scan on metric_data d  (cost=0.00..3753150.28 rows=29336784 width=20)
          Filter: ((t &gt;= '2012-02-05 00:00:00'::timestamp without time zone)
               AND (t &lt;= '2012-05-05 00:00:00'::timestamp without time zone))
    -&gt;  Hash  (cost=270.44..270.44 rows=68 width=13)
          -&gt;  Seq Scan on metrics s  (cost=0.00..270.44 rows=68 width=13)
                Filter: ((sym)::text = ANY ('{cpu,mem}'::text[]))
  </code></pre>