Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Why does PostgreSQL sequentially scans the table for COUNT(*) query, while there is a very small and indexed primary key?

share|improve this question
up vote 8 down vote accepted

The official wiki pages give an answer to that:

[...] The reason why this is slow is related to the MVCC implementation in PostgreSQL. The fact that multiple transactions can see different states of the data means that there can be no straightforward way for "COUNT(*)" to summarize data across the whole table; PostgreSQL must walk through all rows, in some sense. This normally results in a sequential scan reading information about every row in the table. [...]

Furthermore, you could try an ANALYZE to rebuild the info for the query planer.

You should get a better performance using COUNT(an uniquly indexed field) but if this is very big, a seq scan is the only way to do it.

If you need very quick numbers and are not afraid of querying the schema, you can do the following

SELECT reltuples FROM pg_class WHERE oid = 'your_table'::regclass

But don't rely on this values as it is only an "estimated" (although often the exact) number of tuples in the table.

share|improve this answer
I don't think this is correct. I haven't read anything anywhere, where COUNT(pk) will improve performance. I think it will always do a seq-scan – vol7ron Sep 14 '11 at 14:01
Without a where clause you are correct, a seq scan will be performed. With a sufficiently select where clause postgresql CAN use an index, but keep in mind it WILL go back to the table to verify the visibility of the tuples it's reporting on. – Scott Marlowe Sep 26 '11 at 20:35

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.