pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Erik Jones <erik@myemma.com>
To: Jamie Tufnell <diesql@googlemail.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: How to keep at-most N rows per group? periodic DELETEs or constraints or..?
Date: Tue, 8 Jan 2008 10:30:28 -0600
Message-ID: <D71EBDA2-B18D-4722-B291-B4A7E2C49D09@myemma.com> (raw)
In-Reply-To: <b0a4f3350801080624k2088c96aq21c511873959aa87@mail.gmail.com>
References: <b0a4f3350801080624k2088c96aq21c511873959aa87@mail.gmail.com>


On Jan 8, 2008, at 8:24 AM, Jamie Tufnell wrote:

> Hi,
>
> I have a table that stores per-user histories of recently viewed items
> and I'd like to limit the amount of history items to <= 50 per user.
> I'm considering doing this with a query run from cron every so often
> but I'm not happy with what I've come up with so far, and since it's a
> quite active table I thought I'd ask here to see if there's a more
> efficient way.
>
> Right now the table structure is as follows...
>
> user_item_history: id (PK), user_id (FK), item_id (FK), timestamp
>
> For user_ids that have more than 50 rows, I want to keep the most
> recent 50 and delete the rest.

Create an row trigger that fires after insert containing something  
along the lines of :

DELETE FROM user_item_history
WHERE id IN (SELECT id
			   FROM user_item_history
			   WHERE user_id=NEW.user_id
			   ORDER BY timestamp DESC
			   OFFSET 50);
			
Erik Jones

DBA | Emma®
erik@myemma.com
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com






view thread (13+ messages)  latest in thread

Message-ID: <D71EBDA2-B18D-4722-B291-B4A7E2C49D09@myemma.com>
Permalink:  ../D71EBDA2-B18D-4722-B291-B4A7E2C49D09@myemma.com/
Also on:    postgresql.org/message-id/D71EBDA2-B18D-4722-B291-B4A7E2C49D09@myemma.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: erik@myemma.com, diesql@googlemail.com
  Subject: Re: How to keep at-most N rows per group? periodic DELETEs or constraints or..?
  In-Reply-To: <D71EBDA2-B18D-4722-B291-B4A7E2C49D09@myemma.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox