X-Original-To: pgsql-sql-postgresql.org@postgresql.org Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id AB8769FA65C for ; Wed, 21 Jun 2006 14:56:26 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 26169-08 for ; Wed, 21 Jun 2006 14:56:21 -0300 (ADT) X-Greylist: delayed 00:05:52.56372 by SQLgrey- Received: from coe.tamu.edu (edsun.coe.tamu.edu [165.91.232.6]) by postgresql.org (Postfix) with ESMTP id 4B6879F9CC1 for ; Wed, 21 Jun 2006 14:56:19 -0300 (ADT) Received: (from root@localhost) by bruner.coe.tamu.edu (8.13.1/8.13.1) id k5LHnrcV005972; Wed, 21 Jun 2006 12:49:53 -0500 Received: from coe.tamu.edu (coe.tamu.edu [165.91.232.6]) by coe.tamu.edu (8.11.7p2+Sun/8.12.11) with ESMTP id k5LHnKL21433; Wed, 21 Jun 2006 12:49:20 -0500 (CDT) Date: Wed, 21 Jun 2006 12:49:20 -0500 (CDT) From: "Ben K." To: Jeff Frost cc: pgsql-sql@postgresql.org Subject: Re: keeping last 30 entries of a log table In-Reply-To: Message-ID: References: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed X-Virus-Scanned: by AMaViS 0.3.12 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200606/246 X-Sequence-Number: 25482 > I need to write a function which inserts a log entry in a log table and only > keeps the last 30 records. I was thinking of using a subquery similar to the > following: > > insert into log (account_id, message) values (1, 'this is a test); > delete from log where account_id = 1 and id not in ( select id from log > where account_id = 1 order by timestamp desc limit 30); > > I'm wondering if there is a more performance oriented method of doing the > delete that I'm not thinking of. Just for the sake of alternatives - create sequence cy30 maxvalue 30 cycle; insert into log values(select generate_series(1,30), 'dummy'); INSERT 0 30 update log set des='....' where account_id=(select nextval('cy30')); UPDATE 1 There are details to consider I guess. For example what if an update fails and the sequence already advanced... Also, since we cycle the id, for sorting, we'll need to add timestamp or something similar. My 2 pence... P.S. This A) failed me and I wonder if this is supposed to be so or if it's just a place where no one treaded on ?? B) works fine except it doesn't advance the sequence. A) update tc set des='b' where id=nextval('cy30')::int; UPDATE 30 B) update tc set des='c' where id=currval('cy30'); UPDATE 1 Regards, Ben K. Developer http://benix.tamu.edu