Keep only N last records in SQLite database, sorted by date

ahmd0 picture ahmd0 · Jun 30, 2011 · Viewed 13.8k times · Source

I have an SQLite database that I need to do the following: Keep only last N records, sorted by date. How do you do that?

Answer

Jacob Eggers picture Jacob Eggers · Jun 30, 2011

To delete all but the latest 10 records.

delete
from test
where id not in (
    select id
    from test
    order by date desc
    limit 10
)