X-Original-To: pgsql-sql@postgresql.org Received: from localhost (developer.postgresql.org [64.117.224.193]) by developer.postgresql.org (Postfix) with ESMTP id E3F679264EA for ; Mon, 2 Jun 2003 14:28:08 -0400 (EDT) Received: from developer.postgresql.org ([64.117.224.193]) by localhost (developer.postgresql.org [64.117.224.193]) (amavisd-new, port 10024) with ESMTP id 54836-06 for ; Mon, 2 Jun 2003 14:27:57 -0400 (EDT) Received: from anchor-post-35.mail.demon.net (anchor-post-35.mail.demon.net [194.217.242.85]) by developer.postgresql.org (Postfix) with ESMTP id 8A8909264E6 for ; Mon, 2 Jun 2003 14:27:57 -0400 (EDT) Received: from mwynhau.demon.co.uk ([193.237.186.96] helo=mainbox.archonet.com) by anchor-post-35.mail.demon.net with esmtp (Exim 3.36 #2) id 19Mu2F-0000DQ-0Z; Mon, 02 Jun 2003 19:27:55 +0100 Received: from localhost (localhost.localdomain [127.0.0.1]) by mainbox.archonet.com (Postfix) with ESMTP id 613071749D; Mon, 2 Jun 2003 19:27:54 +0100 (BST) Received: from client.archonet.com (client.archonet.com [192.168.1.16]) by mainbox.archonet.com (Postfix) with ESMTP id C38881749C; Mon, 2 Jun 2003 19:27:53 +0100 (BST) Content-Type: text/plain; charset="iso-8859-1" From: Richard Huxton Organization: Archonet Ltd To: Samuel Tardieu , pgsql-sql@postgresql.org Subject: Re: Maintaining a counter up-to-date Date: Mon, 2 Jun 2003 19:27:58 +0100 User-Agent: KMail/1.4.3 References: <871xyc5vmw.fsf@inf.enst.fr> In-Reply-To: <871xyc5vmw.fsf@inf.enst.fr> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Message-Id: <200306021927.58636.dev@archonet.com> X-Virus-Scanned: by AMaViS snapshot-20020531 X-Virus-Scanned: by amavisd-new X-Archive-Number: 200306/24 X-Sequence-Number: 13782 On Monday 02 Jun 2003 4:47 pm, Samuel Tardieu wrote: > I have an "ips" table with 100000+ records, each record having a > "catid" field representing its category. "catid" references a row in a > table called "categories". > > For statistics purpose (generation of images with the evolution of the > number of rows by category), I am trying to reduce the load on the > database. > > The request I was doing at the beginning was: > > SELECT catid, COUNT(*) FROM ips GROUP BY catid; > > I then added a "nentries" field to the "categories" table with some > rules to maintain the counters up-to-date: > > CREATE RULE cat_ins AS [snip] > This works fine when inserting, deleting or updating one row in the > "ips" table. However, when i/d/u several rows at a time with the same > "catid", I only got an increment or decrement by one of the counter. You want to use triggers not rules here (see the "server programming" and= =20 "procedural language" manual sections). A trigger will be fired for each ro= w=20 inserted/deleted/updated. Of course this means it will be fired 5000 times= =20 for 5000 updated rows. --=20 Richard Huxton