Best query to only keep latest 30 records?

I was thinking on using this query.

DELETE * FROM `tableName` WHERE `timestamp` NOT IN (SELECT * FROM tableName SORT BY `timestamp` DESC LIMIT 30)

the query will be used to keep the most recent 30 records which have a primary of key of the unix timestamp. I have alot of records but i will only keep the most recent 30.

Looks fine to me.

Cool, i was just curious if there was better way or better query to do it. perfomance wise. Since I dont SQL much

Sorry I responded without really looking. There are a couple issues with this query.

You only want to select timestamp in the sub-query (not *) since you are building an array of timestamp values. Next, the sub-query for IN() does not support sorting or limiting. There is a workaround though :slight_smile:

DELETE FROM `tableName` WHERE `timestamp` NOT IN (SELECT * FROM (SELECT `timestamp` FROM `tableName` ORDER BY `timestamp` DESC LIMIT 30) AS `stamps_to_keep`)

Basically what this does is create a temporary table called stamps_to_keep then SELECT * FROM stamps_to_keep

Thanks Matt,

By the way the sort by that was a mistake i know that is order by not sort by.

Sponsor our Newsletter | Privacy Policy | Terms of Service