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

后端 未结 4 1305
渐次进展
渐次进展 2020-12-13 15:27

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?

4条回答
  •  孤城傲影
    2020-12-13 15:56

    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)

提交回复
热议问题