Reputation: 89
I am trying to fetch the last row from my SQLite database. Until now i have tried max,sql_sequence but nothing seems to work. I have to fetch the row values and assign it to a class variable. Any help is appreciated as I am new to SQLite and Android. Thanks..
Upvotes: 6
Views: 17266
Reputation: 256
You can use modified query to in last row....but you have to sort in a order using any column like in my case I have a serial_no column in my Employee table so my query is
SELECT * FROM Employee ORDER BY serial_no DESC LIMIT 1
Upvotes: 0
Reputation: 6096
If you have already got the cursor
, then this is how you may get the last record from cursor
:
cursor.moveToPosition(cursor.getCount() - 1);
then use cursor
to read values
or
do it like this
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
or
SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE);
Upvotes: 13
Reputation: 2716
There is usually a table called sqlite_sequence
which stores the highest primary key of all the tables in the SQLite db. So use the following
String selectQuery = "SELECT * FROM sqlite_sequence WHERE name = table_name";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
Upvotes: 1
Reputation: 1052
Try This It May Help You It Gives Last Record Of Your Table
Cursor mCursor = db.rawQuery("Select * from TableName", null);
mCursor.moveToLast();
Now Get The Data From The Cursor
Upvotes: 1
Reputation: 116177
This should do what you want:
SELECT *
FROM food_table
ORDER BY _id DESC
LIMIT 1
Upvotes: 3