0

I'm trying to keep the 10 most recent entries in my database and delete the older ones. I tried DELETE FROM people ORDER BY id DESC LIMIT $excess, but it just deleted the top 10 entries.

$query = "SELECT * FROM people";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($count > 10) {
    $excess = $count - 10;
    $query = "DELETE FROM people WHERE id IN(SELECT id FROM people ORDER BY id DESC LIMIT '$excess')";
    mysqli_query($conn, $query);
}
Rice_Crisp
  • 1,242
  • 1
  • 16
  • 33

4 Answers4

2

Something like this? Gets the ten latest ids in the subquery, then deletes all of the other ids.

DELETE FROM people WHERE id NOT IN (SELECT id FROM PEOPLE ORDER BY id DESC LIMIT 10)
Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
  • I'm getting #1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' ver. 5.0.91 – Rice_Crisp Jun 26 '13 at 17:41
  • Oh, you're using an older version of MySQL, then. If you can't update, I'd suggest making two queries - one to find the tenth id, and then using that to delete all queries that have older ids. – Joel Hinz Jun 26 '13 at 17:43
2

You can use this:-

DELETE FROM `people`
WHERE id NOT IN (
  SELECT id
  FROM (
    SELECT id
    FROM `people`
    ORDER BY id DESC
    LIMIT 10
  ) 
);

Also your query is logically incorrect and you are fetching the records in descending order. i.e. Latest to older and you are deleting the most recent records. Use ASC instead.

Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49
  • I had to add an alias after the first ")" as suggested by the first comment's link, but it seems to work. Thanks. – Rice_Crisp Jun 26 '13 at 17:59
0

Your logic is all over the place, [you should ORDER BY ASC, not DESC] and your query will take ages if there are [for example] 10,000 entries because you'll have an IN clause with 9,990 entries to compare all 10,000 to.

Select the 10 most recent, and delete where NOT in.

DELETE FROM people
  WHERE id NOT IN(
    SELECT id 
    FROM people
    ORDER BY id DESC
    LIMIT 10
  )
Sammitch
  • 30,782
  • 7
  • 50
  • 77
-1

Maybe find the ID of the 10th element and then delete all rows which are older?

user2520968
  • 358
  • 1
  • 3
  • 11