X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 5944A52A99 for ; Fri, 8 Jul 2005 12:25:49 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 03602-07 for ; Fri, 8 Jul 2005 15:25:46 +0000 (GMT) Received: from jandor.look.ca (theta1.look.ca [207.136.80.122]) by svr1.postgresql.org (Postfix) with ESMTP id 4188E52A53 for ; Fri, 8 Jul 2005 12:25:45 -0300 (ADT) Received: from 216-154-13-109.dsl.look.ca ([216.154.13.109]) by jandor.look.ca with esmtp (Exim 4.20) id 1DqujW-0000Zl-PW; Fri, 08 Jul 2005 15:25:42 +0000 From: Rod Taylor To: Steve Wampler Cc: pgsql-sql@postgresql.org, Bruno Wolff III In-Reply-To: <42CE96AF.3020903@noao.edu> References: <9EF2931D-1097-470D-8ECB-59D00166C96F@apple.com> <60vf3mklue.fsf@dba2.int.libertyrms.com> <42CE89CA.2070607@noao.edu> <20050708143508.GD22725@wolff.to> <42CE96AF.3020903@noao.edu> Date: Fri, 08 Jul 2005 11:22:30 -0400 Message-Id: <1120836150.24708.251.camel@home> Mime-Version: 1.0 X-Mailer: Evolution 2.2.3 FreeBSD GNOME Team Port X-SA-Exim-Mail-From: pg@rbt.ca Subject: Re: Make COUNT(*) Faster? Content-Type: text/plain Content-Transfer-Encoding: 7bit X-SA-Exim-Version: 3.1 (built Tue Feb 24 05:09:27 GMT 2004) X-SA-Exim-Scanned: Yes X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.035 tagged_above=0 required=5 tests=AWL, FORGED_RCVD_HELO X-Spam-Level: X-Archive-Number: 200507/73 X-Sequence-Number: 22051 > So, leave COUNT(*) alone. But it would be very handy to have a > way to get an approximate table size that is more accurate than is > provided by a pg_class.reltuples that is only updated on vacuums. Create 2 sequences, one for counting tuple additions and one for counting tuple deletions. When you INSERT a tuple, bump the "added" sequence (select nextval()); When you DELETE a tuple, bump the "deleted" sequence (select nextval()); To retrieve an approximate count, take the current value of both sequences (select directly -- don't use currval) and subtract the "deletes" from the "adds". This is a very fast tracking mechanism with the catch that it does not handle rollbacks -- but you only wanted approximate. Put all of the logic inside a pair of triggers and a function within the DB. --