I create an Android app that has "recents history". I would like to limit the size of this table to a maximum of 50 rows (according to their insert date).
I saw several threads that talk about limiting the number of deleted rows, but I'm not sure if this feature is even enabled in Android's SQLite.
Can anyone help here?
Thanks
You use the LIMIT clause to constrain the number of rows returned by the query. For example, a SELECT statement may return one million rows. However, if you just need the first 10 rows in the result set, you can add the LIMIT clause to the SELECT statement to retrieve 10 rows.
The max_page_count PRAGMA can be used to raise or lower this limit at run-time. 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.
Try to zip it and use zipinput stream while unpacking your database from assets. Anyway, android will zip your 14mb database when you create your apk anyway (which will be unzipped during install), so I guess your apk will be around 5-6mb in size. Android will zip automatically when creating/exporting apk file?
Typically to get a specific row you can always request them by rowid , e.g. SELECT name FROM UnknownTable WHERE rowid = 1; However, there are some atypical situations that preclude this. You'll really want to read up on rowids to ensure that your table is going to behave as you want.
Create a trigger
CREATE TRIGGER delete_till_50 INSERT ON _table WHEN (select count(*) from _table)>50 BEGIN DELETE FROM _table WHERE _table._id IN (SELECT _table._id FROM _table ORDER BY _table._id limit (select count(*) -50 from _table )); END;
EDIT:
You can changeDELETE FROM ... WHERE ... IN ...
toDELETE FROM ... WHERE ... NOT IN ...
as Mojo Risin wrote. I'm not sure about difference of performance for large tables for using IN
and NOT IN
, but for your problem it's no difference.
I think sql can't manage the number of rows in your table so you'll have to manage it by yourself. You can execute query after data insertion that will reduce the data - something like this should work
DELETE FROM table where _id NOT IN (SELECT _id from table ORDER BY insertion_date DESC LIMIT 50)
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