Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I limit the number of rows in Android SQLite table

Tags:

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

like image 397
Gilad Avatar asked Jul 19 '11 10:07

Gilad


People also ask

How do I limit the number of rows returned?

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.

How many rows can a SQLite table hold?

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.

How do I reduce the size of my SQLite database?

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?

How do I SELECT a specific row in SQLite?

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.


2 Answers

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 change
DELETE FROM ... WHERE ... IN ...
to
DELETE 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.

like image 55
pawelzieba Avatar answered Oct 05 '22 21:10

pawelzieba


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) 
like image 45
Mojo Risin Avatar answered Oct 05 '22 19:10

Mojo Risin