tags:

views:

106

answers:

4

I have a simple table where one of the field is a date column. I can select the most recent X records by doing

Select * from MyTable order by last_update desc limit X

But how do I efficiently delete those column? Is subselect the quickest?

+2  A: 

You can do "delete from where" in exactly the same way, with the same conditions as the original query. e.g:

DELETE FROM Person WHERE Person.name = "jeff"

or

DELETE FROM Person WHERE Person.joinTime > 12001234567 LIMIT 100

If you want to delete a range (e.g most recent 10) you could try:

DELETE * FROM Person WHERE id >= ( LAST_INSERT_ID() - 10 );
jgubby
The `12001234567` could also be replaced with a select subquery that finds the timestamp for the cutoff record.
Joel Coehoorn
My table does not have an id field, only dates. None of your queries does what I want.
erotsppa
+1  A: 

Perhaps something like:

DELETE FROM MyTable WHERE rowid IN
(SELECT rowid FROM MyTable ORDER BY last_update DESC LIMIT X);
kerchingo
Would the equals operator work as expected?
Simon Gibbs
should this be "IN" instead of "="
Matthew Whited
Indeed it should, I have corrected.
kerchingo
This won't work in `MySQL`, `IN (SELECT ... LIMIT)` is not supported.
Quassnoi
+2  A: 

If I recall correctly the IN clause accepts a sub select. Could be wrong.

DELETE FROM Person 
WHERE 
  Person.ID IN ( 
     SELECT t.ID 
     FROM 
        Person t 
     ORDER BY 
        t.joinTime DESC
     LIMIT X
   )
Simon Gibbs
if you want the newest should it be ORDER BY t.joinTime DESC?
Matthew Whited
IN is very inefficient. You should always do a JOIN instead of IN ( subselect)
DVK
How would you do it with a join instead?
erotsppa
This won't work in `MySQL`, `IN (SELECT ... LIMIT)` is not supported.
Quassnoi
+1  A: 
DELETE  d.*
FROM    mytable d
LEFT JOIN
        (
        SELECT  id
        FROM    mytable
        ORDER BY
                last_update DESC
        LIMIT   10
        ) q
ON      d.id = q.id
WHERE   q.id IS NULL

If your are using MySQL, this is the preferred solution, since IN (SELECT ... LIMIT) does not work in MySQL.

See this entry in my blog for more details:

Quassnoi