0

database schema

I have a database with following columns(screenshot attached)

_id = INTEGER PRIMARY KEY

guid = TEXT(unique id of the image)

pubDate= LONG(time since epoch)

imgsrc = BLOB(image byte)

The requirement is such that i want to keep only images which are downloaded today. I want to delete stale data...i.e yesterdays data.

For ex consider id = 1 with guid = 471c9744666b6f51

This image was downloaded on Wed Dec 26 2012 17:11:05, so database should contain data only for Dec 26 and not Dec 25. Its not necessary that the first pubdate will be have today's date. So, probably first we need to sort the db by pubdate in desc-ding order and then use the first pubdate as an input to delete older data.

Any help as to how to form a SQL statement will be highly appreciated.

Answer:Ended up doing something like this..

long maxDate = 0;

Cursor cursor = getApplicationContext().getContentResolver().query(IMAGES_URI, null, null, null, PUB_DATE + " DESC ");

if (cursor != null && cursor.moveToNext()) {
maxDate = cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseHelper.PUB_DATE));
cursor.close();
}
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(maxDate);
cal.add(Calendar.HOUR, -12);

int delcount = getApplicationContext().getContentResolver().delete(IMAGES_URI, PUB_DATE + " <= " + cal.getTimeInMillis(), null);

1 Answer 1

3
String sql = "DELETE FROM myTable WHERE pubDate <= date('now','-1 day')"; 
db.execSQL(sql);

EDIT:

String sql = "DELETE FROM myTable WHERE pubDate NOT IN (SELECT MAX(pubDate) FROm myTable)"; 
db.execSQL(sql);

EDIT: Final Version

DELETE FROM myTable WHERE pubDate NOT IN (SELECT pubdate FROM mytable 
WHERE pubDate < datetime((SELECT MAX(pubDate) FROM myTable),'-1 days'))
Sign up to request clarification or add additional context in comments.

3 Comments

thanks. But i think instead of using 'now'(which is system time), i would prefer to use highest time stored in db. How to go about it?
@Yaqub I think there's an error in your last query. The subquery after NOT IN will select exactly one record every time. So, if there's more than one record in a given day, those will be deleted too. In fact, this DELETE query will preserve exactly one record (the last inserted) if I'm correct.
Here's my version: "DELETE FROM myTable WHERE pubDate NOT IN (SELECT pubdate FROM mytable WHERE pubDate < datetime((SELECT MAX(pubDate) FROM myTable),'-1 days'))"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.