Re: keeping last 30 entries of a log table

From: Daniel CAUNE <d(dot)caune(at)free(dot)fr>
To: 'Jeff Frost' <jeff(at)frostconsultingllc(dot)com>, pgsql-sql(at)postgresql(dot)org
Subject: Re: keeping last 30 entries of a log table
Date: 2006-06-17 15:16:13
Message-ID: 0J10001JS4N1G9G0@VL-MH-MR001.ip.videotron.ca
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

> 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

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Richard Broersma Jr 2006-06-17 20:08:20 any additional date_time functions?
Previous Message Aaron Bono 2006-06-17 14:52:50 Re: concurrency problem