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?
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.
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.
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.
Below query will delete data older than 2 days:
String sql = "DELETE FROM myTable WHERE Save_Date <= date('now','-2 day')";
db.execSQL(sql);
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'.
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With