Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the number of rows in a room database

How can I limit the number of rows in an Android room database by removing the oldest item in the row and inserting the newest one?

I am guessing its a standard query when adding an item to the database?

EDIT: I want to limit a database table to have a max row count of say 20. If that limit is reached, we remove the oldest item and insert the new one by keeping the current row count to 20.

like image 715
Stillie Avatar asked Sep 13 '17 09:09

Stillie


People also ask

Is room database deprecated?

This field is deprecated.

How delete all data from table in room?

3.1 Add the Clear all data menu option Run your app. In the Options menu, select Clear all data. All words should disappear. Restart the app.

Is room database persistent?

Room is a persistence library that's part of Android Jetpack. Room is an abstraction layer on top of a SQLite database. SQLite uses a specialized language (SQL) to perform database operations. Instead of using SQLite directly, Room simplifies the chores of setting up, configuring, and interacting with the database.

What is room in SQLite?

The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In particular, Room provides the following benefits: Compile-time verification of SQL queries.


2 Answers

Here is sample solution:

Query is :

@Query("SELECT * FROM user LIMIT :limit OFFSET :offset")     User[] loadAllUsersByPage(int limit,int offset); 

Here, it will give a list of user based on limit and offset.

if loadAllUsersByPage(2,0) it will return first 2 rows from table.

if loadAllUsersByPage(2,1) it will return 2nd and 3rd rows from table.

but if loadAllUsersByPage(-1,10) then it will serve first 10 rows from table.

like image 163
Md. Sajedul Karim Avatar answered Sep 19 '22 11:09

Md. Sajedul Karim


I think you can insert the data into your table then remove all the rows except last 20 (limit)

To delete you can use the following query

DELETE FROM tableName where id NOT IN (SELECT id from tableName ORDER BY id DESC LIMIT 20)

In this case, id is the primary key which is set to auto increment. You can use date as key as well if you are storing them by date

like image 23
Kunu Avatar answered Sep 20 '22 11:09

Kunu