partiz
partiz

Reputation: 1216

Delete all but top n from database table in SQLite for java/android

I am new in java but I am trying to code:

      SQLiteDatabase db = this.getWritableDatabase();
        //db.execSQL("delete from " + TABLE_BOOKMARKS + " where " + KEY_ID + "  not in (select " + KEY_ID + " from " + TABLE_BOOKMARKS + " order by " + KEY_ID + " limit 10)" );
        //db.execSQL("DELETE FROM " + TABLE_BOOKMARKS + " WHERE " + KEY_ID + " NOT IN (SELECT TOP 10 " + KEY_ID + " FROM " + TABLE_BOOKMARKS + ")" );

        db.execSQL("Delete From "+TABLE_BOOKMARKS+"  where "+ KEY_ID  + " not in (Select Top 10 "+ KEY_ID +" from "+ TABLE_BOOKMARKS + " order by " + KEY_ID +")");
        db.close(); // Closing database connection

you can see in the code, I have tried in 3 different ways but when I run it my application returns error and stops!

I got this error:

android.database.sqlite.SQLiteException: near "10": syntax error: , while compiling: Delete From bookmarks where id not in (Select Top 10 id from bookmarks order by id)

Upvotes: 0

Views: 378

Answers (1)

Aiken
Aiken

Reputation: 88

You can try

db.execSQL("Delete From "+TABLE_BOOKMARKS+"  where "+ KEY_ID  + " not in (Select "+ KEY_ID +" from "+ TABLE_BOOKMARKS + " order by " + KEY_ID +" limit 10)");

Upvotes: 1

Related Questions