Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete oldest mysql table records, but leave 1000 newest

Tags:

sql

mysql

What query deletes oldest mysql table records, but leave 1000 newest. does not matter how mush records are there - I need 1000 newest of them.

like image 864
Prostitutor Avatar asked Jan 17 '26 18:01

Prostitutor


1 Answers

delete from your_table
where id not in
(
   select * from 
   (
      select id from your_table
      order by id desc
      limit 1000
   ) x
)

The inner select returns the most recent 1000 ids. The other delete deletes all records but the ones from the inner select.

like image 135
juergen d Avatar answered Jan 19 '26 18:01

juergen d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!