Is there an MySQL query which would delete all values from a table, except the latest 20 entries (ordered by id
)?
So let's say I have a table notifications
, where 1000 notifications reside and I want to keep only latest 20.
If SQL is not enough for this, using php
is optional.
I have a few ideas how to do this, but I don't really consider them efficient.
You can find the latest id, store it into local variable and then delete everything below this id:
set @tmp_id := (select id from notifications order by id desc limit 20,1);
delete from notifications where id <= @tmp_id;
I have not ran this, so I apologize if it doesn't work, but according to the SQL syntax for delete this should work.
DELETE FROM notifications ORDER BY id ASC LIMIT ((SELECT COUNT(*) FROM notifications)-20);
$result = $mysqli->query("SELECT ids FROM notifications");
$count = $result->num_rows;
$count -=20;
$result = $mysqli->query("DELETE FROM notifications ORDER BY id ASC LIMIT $count");