Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql statement to delete records older than XXX as long as there are more than YY rows

Tags:

sql

datetime

Assume a table with the following columns:

pri_id, item_id, comment, date

What I want to have is a SQL query that will delete any records, for a specific item_id that are older than a given date, BUT only as long as there are more than 15 rows for that item_id.

This will be used to purge out comment records older than 1 year for the items but I still want to keep at least 15 records at any given time. This way if I had one comment for 10 years it would never get deleted but if I had 100 comments over the last 5 days I'd only keep the newest 15 records. These are of course arbitrary record counts and date timeframes for this example.

I'd like to find a very generic way of doing this that would work in mysql, oracle, postgres etc. I'm using phps adodb library for DB abstraction so I'd like it to work well with that if possible.

like image 885
Matt P Avatar asked Oct 16 '08 22:10

Matt P


People also ask

How delete large number of rows in SQL Server?

Deleting large portions of a table isn't always the only answer. If you are deleting 95% of a table and keeping 5%, it can actually be quicker to move the rows you want to keep into a new table, drop the old table, and rename the new one. Or copy the keeper rows out, truncate the table, and then copy them back in.

What is batch delete in SQL Server?

Users can delete records from the database either individually or in batches.


1 Answers

Something like this should work for you:

delete
from
  MyTable
where
  item_id in
  (
    select
      item_id
    from
      MyTable
    group by
      item_id
    having
      count(item_id) > 15
  )
  and
    Date < @tDate
like image 91
Robert C. Barth Avatar answered Oct 06 '22 18:10

Robert C. Barth