title: Why does this SUM() function take so long in PostgreSQL?
body: <p>This is my query:</p>
  
  <pre><code>SELECT SUM(amount) FROM bill WHERE name = 'peter'
  </code></pre>
  
  <p>There are 800K+ rows in the table. <code>EXPLAIN ANALYZE</code> says:</p>
  
  <pre><code>Aggregate  (cost=288570.06..288570.07 rows=1 width=4) (actual time=537213.327..537213.328 rows=1 loops=1)
  -&gt;  Seq Scan on bill  (cost=0.00..288320.94 rows=498251 width=4) (actual time=48385.201..535941.041 rows=800947 loops=1)
  Filter: ((name)::text = 'peter'::text)
  Rows Removed by Filter: 8
  Total runtime: 537213.381 ms
  </code></pre>
  
  <p>All rows are affected, and this is correct. But why so long? A similar query without <code>WHERE</code> runs way faster:</p>
  
  <pre><code>ANALYZE EXPLAIN SELECT SUM(amount) FROM bill
  Aggregate  (cost=137523.31..137523.31 rows=1 width=4) (actual time=2198.663..2198.664 rows=1 loops=1)
  -&gt;  Index Only Scan using idx_amount on bill  (cost=0.00..137274.17 rows=498268 width=4) (actual time=0.032..1223.512 rows=800955 loops=1)
  Heap Fetches: 533399
  Total runtime: 2198.717 ms
  </code></pre>
  
  <p>I have an index on <code>amount</code> and an index on <code>name</code>. Have I missed any indexes?</p>
  
  <p>ps. I managed to solve the problem just by adding a new idex <code>ON bill(name, amount)</code>. I didn't get why it helped, so let's leave the question open for some time...</p>