Quantcast
Channel: Question and Answer » postgresql
Viewing all articles
Browse latest Browse all 1138

PostgreSQL not using index during count(*)

$
0
0

I have a COUNT(*) query in PostgreSQL that runs often, and looks like:

SELECT COUNT(*) 
  FROM customer 
 WHERE source_id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);

This query takes between 30-60 seconds to run and searches millions of records.

EXPLAIN ANALYZE shows it’s doing a sequential scan, so I created the index:

CREATE INDEX customer_by_source ON customer (source_id)
WHERE source_id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);

However, EXPLAIN ANALYZE still shows it’s doing a sequential scan and isn’t using the index.

How do I speed up this query and make it use the index?

Edit: My Postgres version is 9.3.3. The table has about 20 million records, divided pretty evenly among each source_id, of which another 5 aren’t included in the list.


Viewing all articles
Browse latest Browse all 1138

Trending Articles