Delete oldest records from database

前端 未结 3 538
悲哀的现实
悲哀的现实 2020-12-23 21:01

I have a database with 1000 records. I am trying to create an SQL statement so if the number of records grows above 1000, then the oldest records are deleted (i.e. the new r

3条回答
  •  梦毁少年i
    2020-12-23 21:43

    If you use an auto-increment field, you can easily write this to delete the oldest 100 records:

    DELETE FROM mytable WHERE id IN (SELECT id FROM mytable ORDER BY id ASC LIMIT 100)
    

    Or, if no such field is present, use ROWID:

    DELETE FROM mytable WHERE ROWID IN (SELECT ROWID FROM mytable ORDER BY ROWID ASC LIMIT 100)
    

    Or, to leave only the latest 1000 records:

    DELETE FROM mytable WHERE ROWID IN (SELECT ROWID FROM mytable ORDER BY ROWID DESC LIMIT -1 OFFSET 1000)
    

提交回复
热议问题