title: Why this query is not using index only scan in postgresql
body: <p>I have a table with 16 columns, in which there are a primary key and a column to store values.
  I want to select all the values in a certain range.
  The value column (easyid) has been indexed.</p>
  
  <pre><code>create table tb1 (
      id Int primary key,
      easyid Int,
      .....
  )
  create index i_easyid on tb1 (easyid)
  </code></pre>
  
  <p>Other info: postgresql 9.4, no auto vacuum.
  The sql is like this.    </p>
  
  <pre><code>select "easyid" from "tb1" where "easyid" between 12183318 and 82283318
  </code></pre>
  
  <p>Theoretically postgresql should use index only scan on <code>i_easyid</code>. <del>It only do index only scan when the range <code>"easyid" between A and B</code> is small.
  When the range is large, namely <code>B-A</code> is a  pretty big number, postgresql uses bitmap index scan on <code>i_easyid</code> and then bit heap scan on <code>tb1</code>.</del></p>
  
  <p>I was wrong to say index scan only or not depends on the range size.
  I tried the same query with different parameters, sometimes it is index scan only sometimes it is not.</p>
  
  <p>The table <code>tb1</code> is very large up to 17G. <code>i_easyid</code> is 600MB. </p>
  
  <p>Here is the explain of sql. And I don't understand why 4000 rows can cost more than 10 seconds.</p>
  
  <pre><code>sample_pg=# explain analyze select easyid from tb1 where "easyid" between 152183318 and 152283318;
                                                           QUERY PLAN
  ----------------------------------------------------------------------------------------------------------------------------
   Bitmap Heap Scan on tb1  (cost=97.70..17227.71 rows=4416 width=4) (actual time=1.155..14346.311 rows=5004 loops=1)
     Recheck Cond: ((easyid &gt;= 152183318) AND (easyid &lt;= 152283318))
     Heap Blocks: exact=4995
     -&gt;  Bitmap Index Scan on i_easyid  (cost=0.00..96.60 rows=4416 width=0) (actual time=0.586..0.586 rows=5004 loops=1)
           Index Cond: ((easyid &gt;= 152183318) AND (easyid &lt;= 152283318))
   Planning time: 0.080 ms
   Execution time: 14348.037 ms
  (7 rows)
  </code></pre>
  
  <p>Here is an example of index only scan:</p>
  
  <pre><code>sample_pg=# explain analyze verbose select easyid from tb1 where "easyid" between 32280318 and 32283318;
                                                                 QUERY PLAN
  -----------------------------------------------------------------------------------------------------------------------------------------
   Index Only Scan using i_easyid on public.tb1  (cost=0.44..281.82 rows=69 width=4) (actual time=14.585..160.624 rows=33 loops=1)
     Output: easyid
     Index Cond: ((tb1.easyid &gt;= 32280318) AND (tb1.easyid &lt;= 32283318))
     Heap Fetches: 33
   Planning time: 0.085 ms
   Execution time: 160.654 ms
  (6 rows)
  </code></pre>