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 96A889FA5E9 for ; Sat, 17 Jun 2006 09:16: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 72097-10 for ; Sat, 17 Jun 2006 09:16:21 -0300 (ADT) X-Greylist: delayed 01:00:05.729321 by SQLgrey- Received: from relais.videotron.ca (relais.videotron.ca [24.201.245.36]) by postgresql.org (Postfix) with ESMTP id CF1B09FA430 for ; Sat, 17 Jun 2006 09:16:21 -0300 (ADT) Received: from lythanhphu ([66.130.229.163]) by VL-MH-MR001.ip.videotron.ca (Sun Java System Messaging Server 6.2-2.05 (built Apr 28 2005)) with ESMTP id <0J10001JR4N1G9G0@VL-MH-MR001.ip.videotron.ca> for pgsql-sql@postgresql.org; Sat, 17 Jun 2006 07:16:13 -0400 (EDT) Date: Sat, 17 Jun 2006 11:16:13 -0400 From: Daniel CAUNE Subject: Re: keeping last 30 entries of a log table In-reply-to: To: 'Jeff Frost' , pgsql-sql@postgresql.org Message-id: <0J10001JS4N1G9G0@VL-MH-MR001.ip.videotron.ca> MIME-version: 1.0 X-MIMEOLE: Produced By Microsoft MimeOLE V6.00.2900.2869 X-Mailer: Microsoft Office Outlook, Build 11.0.6353 Content-type: text/plain; charset=utf-8 Content-transfer-encoding: 7BIT Thread-index: AcaRtfJ8slSJN/gvRZ+LLedb9oVJogAaiEnQ X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200606/219 X-Sequence-Number: 25455 > 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. > Depending on whether id is a kind of auto-incremented column that never cycles, I would suggest something like: DELETE FROM log WHERE account_id = 1 AND id < ( SELECT MIN(id) FROM log WHERE account_id = 1 ORDER BY timestamp DESC LIMIT 30); I think there will be a performance difference with your method when the number of records to be deleted is huge. -- Daniel