Search code examples
javaandroidsqliteandroid-sqlite

android sqlite delete rows older than x days using db.delete


I know it is possible to delete rows older than X days using

String sql = "DELETE FROM TABLE WHERE Date <= datetime('now','-7 day')";
db.execSQL(sql);

However db.execSQL(sql) does not return a value and I need to confirm that deletion was successful.

db.delete() returns an int but how to set the WhereClause and whereArgs to delete all rows older than 7 days for example?

String whereClause = ...
new String[] whereArgs=....
int deletedRows = db.delete("TABLE", whereClause , whereArgs); 

Solution

  • You don't need the whereArgs variable if your condition is fixed:

    Date <= datetime('now','-7 day')
    

    So you can do it like this:

    String whereClause = "Date <= datetime('now', '-7 day')"; 
    int deletedRows = db.delete("TABLE", whereClause , null);
    

    If you want to be able to pass the number of days that you want to subtract as a parameter, then you will need whereArgs:

    String[] whereArgs = new String[] {"7"}
    String whereClause = "Date <= datetime('now', '-' || ? || ' day')"; 
    int deletedRows = db.delete("TABLE", whereClause, whereArgs);