Search code examples
performancesqliteandroid-sqliteandroid-cursor

Sqlite Performance When Deleting Table Data


I have a method that deletes all of the records in my local sqlite database.

public void deleteAll() {
    Cursor c = getAllRows();
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
    if (c.moveToFirst()) {
        do {
            deleteRow(c.getLong((int) rowId));
        } while (c.moveToNext());
    }
    c.close();
}

I noticed that if I have about 400+ records (simple rows with about 5 string columns each)to delete it takes about 2 seconds and freezes up my UI. However, if I have anywhere under 100 records it works almost instantly. What I want to know is whether this is normal or if I probably have some code lurking somewhere that is causing performance issues. I'm a beginner, so it wouldn't shock me in the slightest to find out I have some very ugly code locking everything up.


Solution

  • If you want to delete all records in a table then simply call a single query

    truncate your_table
    

    or

    delete from your_table
    

    Try to avoid calling queries all the time which is slow. Rather try to process the data with a single query.