Skip to content
Advertisement

Delete the first 8 rows from an SQLite database

I delete rows in a SQLite table with this:

public void deleteFirstRow()
{
    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cursor = db.query("eventosUTN", null, null, null, null, null, null);

    if(cursor.moveToFirst()) {
        String rowId = cursor.getString(cursor.getColumnIndex("id"));
        db.delete("eventosUTN", "id" + "=?",  new String[]{rowId});
    }
    db.close();
}

I need to delete the first 8 rows when the database has a size bigger than 8 rows, so:

public void checkRowsSize(Events events, Context contex)
{  
    new Thread(new Runnable() { 
        public void run() {
        if(events.getRowCount()>8){
            while(events.getRowCount()>8){
                events.deleteFirstRow(contex);
            }
        }
    }
}).start();
}

The method Events’s getRowCount is:

public int getRowCount(){
    String query = "Select*FROM eventsUTN";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    return cursor.getCount();
} 

But When I set the while loop in checkRowSize it delete the all database. Why this? But If I set:

public void checkRowsSize(Events events, Context contex)
{  
    new Thread(new Runnable() { 
        public void run() {
        if(events.getRowCount()>8){
            events.deleteFirstRow(contex);
        }
    }
}).start();
}

It just delete the first row every time the Activity is created, until the database has a size smaller than 8 rows. So without the while loop it works fine!

Advertisement

Answer

You can delete the first 8 rows when the table has a size bigger than 8 rows with this statement:

delete from eventosUTN
where 
  (select count(*) from eventosUTN) > 8
  and 
  id in (select id from eventosUTN limit 8)

where id is the primary key of your table.
But you should know that what you think as first 8 rows in a table is not always what you get.
Table rows are unordered.
So maybe you should define the logic of this order with the use of an ORDER BY clause like:

delete from eventosUTN
where 
  (select count(*) from eventosUTN) > 8
  and 
  id in (select id from eventosUTN order by id limit 8)

So you can do this in java code like this:

String where = "(select count(*) from eventosUTN) > 8 and id in (select id from eventosUTN order by id limit 8)";
db.delete("eventosUTN", where, null);


If the primary key of your table is integer and has been defined as AUTOINCREMENT which means that it is always increasing and never reused then you could also use this statement:

delete from eventosUTN 
where id < (select id from eventosUTN order by id limit 8, 1)

and in java code:

String where = "id < (select id from eventosUTN order by id limit 8, 1)";
db.delete("eventosUTN", where, null);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement