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?
Assuming you have an id column which is a sequential number (AUTO INCREMENT), you can use the following:
DELETE FROM table_name
WHERE id < (
SELECT MIN(id)
FROM (SELECT id
FROM table_name
ORDER BY id DESC
LIMIT num_of_records_to_keep))
The same query can be used when using a timestamp column (simply replace id with your timestamp column)