Search code examples
javaandroidsqlitesql-delete

SQLite delete query in Android


I'd need your help, I'm starting with Android databases and I have a litte problem/question for update my tables (maybe is a stupid question but is hard for me ) :

I have a table with info about videos, one of the columns is the timestamp for indentify how old is the video. I'd like to delete all rows except the top 10 with higher timestamp.

if the table name is TABLE and the (important) rows are KEY_ID, and KEY_TIMESTAMP:

How can I concat the query1:

SELECT KEY_ID FROM TABLE ORDER BY KEY_TIMESTAMP ASC LIMIT (## dont know what to put here ##)

with the query

DELETE FROM TABLE WHERE KEY_ID = query1

in Android SQLite code? what should I put in between the ## ##


Solution

  • Try using DELETE FROM with a nested SELECT.

    Not tested:

    DELETE 
    FROM TABLE
    WHERE KEY_ID NOT IN
    (
        SELECT TOP 10 KEY_ID 
            FROM TABLE 
            ORDER BY KEY_TIMESTAMP ASC
            LIMIT 10
    )