Re: count(*) slow on large tables

Tom Lane <tgl@sss.pgh.pa.us>

From: Tom Lane <tgl@sss.pgh.pa.us>
To: Bruce Momjian <pgman@candle.pha.pa.us>
Cc: Christopher Browne <cbbrowne@libertyrms.info>, pgsql-performance@postgresql.org
Date: 2003-10-04T16:49:33Z
Lists: pgsql-hackers, pgsql-performance
Bruce Momjian <pgman@candle.pha.pa.us> writes:
> We do have a TODO item:
> 	* Consider using MVCC to cache count(*) queries with no WHERE clause

> The idea is to cache a recent count of the table, then have
> insert/delete add +/- records to the count.  A COUNT(*) would get the
> main cached record plus any visible +/- records.  This would allow the
> count to return the proper value depending on the visibility of the
> requesting transaction, and it would require _no_ heap or index scan.

... and it would give the wrong answers.  Unless the cache is somehow
snapshot-aware, so that it can know which other transactions should be
included in your count.

			regards, tom lane