Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting android SQLite rows older than x days

Tags:

android

sqlite

I want to delete all rows in table MYTABLE which are older than x days. Column SAVE_DATE Long is the time when the row was inserted in table.

I tried this but apparently it deletes all my rows:

long daysInMiliSec = new Date().getTime() - X
            * (24L * 60L * 60L * 1000L);
return db.delete(MYTABLE , SAVE_DATE
            " <= ?", new String[] { "" + daysInMiliSec }

What is wrong?

like image 772
George D Avatar asked Aug 02 '12 05:08

George D


People also ask

How many rows is too many for SQLite?

The theoretical maximum number of rows in a table is 264 (18446744073709551616 or about 1.8e+19). This limit is unreachable since the maximum database size of 281 terabytes will be reached first.

Can you remove any table at any time in SQLite?

SQLite allows you to drop only one table at a time. To remove multiple tables, you need to issue multiple DROP TABLE statements. If you remove a non-existing table, SQLite issues an error.

What is the main limitation of SQLite?

An SQLite database is limited in size to 281 terabytes (248 bytes, 256 tibibytes). And even if it could handle larger databases, SQLite stores the entire database in a single disk file and many filesystems limit the maximum size of files to something less than this.


3 Answers

Below query will delete data older than 2 days:

String sql = "DELETE FROM myTable WHERE Save_Date <= date('now','-2 day')"; 
db.execSQL(sql);
like image 159
Yaqub Ahmad Avatar answered Nov 05 '22 00:11

Yaqub Ahmad


Since it's the first hit on google some more explanation for beginners:
You do not need the time/date functions from the main program you use to access the sqlite DB but use the sqlite date functions directly.

You create the table with the row entry for the age with for example:

CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, text TEXT, age INTEGER)

You write to it with

INSERT INTO test (text, age) VALUES ("bla", datetime('now'))

Here I used 'datetime' because this also will let you later search for hours/minutes/seconds. If you don't need that 'date('now')' is enough.

Here is an explanation for the date function: https://www.sqlite.org/lang_datefunc.html

To select everything older than for example 5 minutes:

SELECT * FROM test WHERE age <= datetime('now', '-5 minutes')

You can see more of those possibilities on the website above under the paragraph 'Modifiers'.

like image 13
user136036 Avatar answered Nov 05 '22 02:11

user136036


Delete data older than 2 days when the timestamp or date field is stored in milliseconds or an epoch integer.

DELETE FROM update_log WHERE timestamp <= strftime('%s', datetime('now', '-2 day'));
like image 3
Brian Feldman Avatar answered Nov 05 '22 02:11

Brian Feldman